mheavers
mheavers

Reputation: 30158

JQuery, JSON - problem with quotation marks in JSON data

I'm trying to read JSON data that includes quotation marks, which effectively escape the string and treat ensuing text like a variable. How do I keep this from happening? Here is the JSON feed (it's built in expression engine, so ignore the curly braces):

<?php echo substr($_SERVER["REQUEST_URI"], strpos($_SERVER["REQUEST_URI"],"=")+1, strpos($_SERVER["REQUEST_URI"],"&")-strpos($_SERVER["REQUEST_URI"],"=")-1);?>([
{exp:channel:entries channel="blog" limit="10" dynamic_start="on" disable="member_data"}
{
    "title": "{exp:url_encode}{title}{/exp:url_encode}",
    "body": "{blog_one_liner}",
    "link": "{blog_image_link}",
    "img" : "{blog_image}"
},
{/exp:channel:entries}
]);

and here's the parsing which happens in jquery:

function loadBlog(){
    $.getJSON("http://superfad.com/work/work_json?callback=?&test=test", blogLoaded);
}

    function blogLoaded(data){


        for (dataIndex in data) {
            var blogTitle = decodeURI(data[dataIndex].title);
            var blogContent = data[dataIndex].body;
            var blogLink = data[dataIndex].link;
            var blogImg = data[dataIndex].img;

            $("#blog_results").append('<li class="blog"><a href="' + blogLink + '" target="_blank"><img class="blog_img" src="' + blogImg + '"/></a><span class="blogtitle">'+ blogTitle + '</span> - '+ blogContent + '</li>');

        };
    }

You can see I tried, for the title, to encode in expression engine (which works fine) and decode in the javascript (which isn't working). I saw JSON has some sort of linkify function, but I couldn't figure out how to do it without switching to JQuery's AJAX functionality. What I'd like to do is avoid the expression engine encoding altogether and do everything with Javascript if possible (and PHP if necessary).

Upvotes: 0

Views: 1916

Answers (2)

Tae-Sung Shin
Tae-Sung Shin

Reputation: 20643

Have you ever tried "unescape('encoded string')"? In order to resolve '+' issue, you can do

// Create a regular expression to search all +s in the string
var lsRegExp = /\+/g;
// Return the decoded string
return unescape(String(psEncodeString).replace(lsRegExp, " ")); 

Reference: http://www.kamath.com/codelibrary/cl006_url.asp

Upvotes: 1

guido
guido

Reputation: 19194

Try with decodeURIComponent() instead of decodeURI().

decodeURI is for complete URLs, while decodeURIComponent works for any string.

Upvotes: 2

Related Questions