tekknolagi
tekknolagi

Reputation: 11012

Parsing JSON returns cryptic error

I have some JSON (https://gist.github.com/tekknolagi/8526671) that I am requesting for a list of my blog posts.

I got some funky errors in the console: enter image description here

And also in JSONLint: enter image description here

I cannot figure out what's wrong. My code:

$(document).ready(function () {
    $.ajax({
    url: '/posts.json',
    type: "GET",
    dataType: "text",
    success: function(data) {
//      data = data.replace(/(\r\n|\n|\r)/gm,"");
        console.log(data);
        var parsed = JSON.parse(data);
        var parsed = data;
        var names = []
        for (var post in parsed) names.push(post.title);
        console.log(names);
        $('#page_holder').pagify({ 
        pages: data,
        default: null
        });
    },
    fail: function (err) {
        console.log(err);
    }
    });
});

And it always fails on the parse. This has been killing me for weeks.

Upvotes: 0

Views: 92

Answers (1)

Felix Kling
Felix Kling

Reputation: 816462

The line that throws the error has this inside the string:

Type \"help\", \"copyright\", \"credits\" or \"license\"

\& is not a valid escape sequence in JSON strings values:


(source: json.org)


"Proof":

["\&foo"]

results in the same error


Since I don't know how the \ got there in the first place, it's not really possible to provide a solution. But to make the JSON valid, you have to remove those (or double them as Pointy pointed out (no pun intended)) (before you generate the JSON). A proper JSON library should actually take care of escaping the \ correctly.

Upvotes: 6

Related Questions