douglascrockford / JSON-js

JSON in JavaScript
http://www.JSON.org/
8.7k stars 4.59k forks source link

Failing to parse this valid JSON #119

Closed stephen147 closed 4 years ago

stephen147 commented 4 years ago

var str = '{ "kind": "youtube#playlistItemListResponse", "etag": "p4VTdlkQv3HQeTEaXgvLePAydmU/Vc3EkgLSTjYGqvhPMXul5T13c6k", "pageInfo": { "totalResults": 19, "resultsPerPage": 50 }, "items": [ { "kind": "youtube#playlistItem", "etag": "p4VTdlkQv3HQeTEaXgvLePAydmU/7hcDWTrN7EFhot4DpXw8fi97qUo", "id": "UExvQXI3RzlNaGtuOG1jTTR2VjE4SlY1RG5EMnJLQUYxNC5CMUM0NzY5NzdEQzlGRjAx", "snippet": { "publishedAt": "2019-12-23T17:23:10.000Z", "channelId": "UCaSq01bKPGAmrOnjpzBFDPQ", "title": "Regal - Repeat", "description": "Released by: Involve Records \n\nRelease/catalogue number: INV008 \n\nRelease date: Jun 15, 2015\n\nBuy and support\nhttp://decks.de/t/regal-alma_mater_ep/c55-r6\n\nhttp://facebook.com/RegalOfficial\nhttp://soundcloud.com/regalmusic\n\nhttp://involverecords.es\nhttp://facebook.com/involverecords\nhttp://soundcloud.com/involve-records\n\nRegal is back on his own imprint with a 4 cuts powerful EP. Two acid cuts, as couldn’t be otherwise, plus two dark, but full of soul, techno tracks for the mental moment of the night.\n\nAll rights reserved for the producers of these tracks.", "thumbnails": { "default": { "url": "https://i.ytimg.com/vi/7QPrJa7z12s/default.jpg", "width": 120, "height": 90 }, "medium": { "url": "https://i.ytimg.com/vi/7QPrJa7z12s/mqdefault.jpg", "width": 320, "height": 180 }, "high": { "url": "https://i.ytimg.com/vi/7QPrJa7z12s/hqdefault.jpg", "width": 480, "height": 360 }, "standard": { "url": "https://i.ytimg.com/vi/7QPrJa7z12s/sddefault.jpg", "width": 640, "height": 480 }, "maxres": { "url": "https://i.ytimg.com/vi/7QPrJa7z12s/maxresdefault.jpg", "width": 1280, "height": 720 } }, "channelTitle": "Channelxyz", "playlistId": "PLoAr7G9Mhkn8mcM4vV18JV5DnD2rKAF14", "position": 0, "resourceId": { "kind": "youtube#video", "videoId": "7QPrJa7z12s" } }, "contentDetails": { "videoId": "7QPrJa7z12s", "videoPublishedAt": "2015-07-02T15:07:27.000Z" } } ] }';
var obj = JSON.parse(str, function (key, value) {
return value;
});
console.log(obj.etag);

The above is failing to parse. Is this user error or something else that may be causing it to fail.

The JSON str variable is valid using an online checker.

The error that's getting returned is:

SyntaxError: Unexpected token 
 in JSON at position 530
    at JSON.parse (<anonymous>)
jamesearl commented 4 years ago

Seems a conflict with the newline escapes and your interpreter vs json linter. It's valid JSON if you drop the single quote wrapping and test it, but when the interpreter grabs the string it handles the \n escapes ahead of the JSON.parse call.

You fix it by escaping the backslash ahead of the newline escapes: \\n

stephen147 commented 4 years ago

I don't quite understand, you mean inside the json2.js

jamesearl commented 4 years ago

No there's nothing wrong with json2.js

I'm saying that the string you're parsing is not the string you think you're parsing, because of the newline (\n) characters.

This fails for the same reason that your input string does: JSON.parse('{"a": "\n"}')

jamesearl commented 4 years ago

See this: https://stackoverflow.com/questions/42068/how-do-i-handle-newlines-in-json

stephen147 commented 4 years ago

Ok, by doing this it worked. I thought that it was a bug but going by that thread it's by design.

Here's the fix:

String.prototype.jsonEscape = function() {
return this.replace(/\n/g, "\\\\n").replace(/\r/g, "\\\\r").replace(/\t/g, "\\\\t");
}

var str = '{ "kind": "youtube#playlistItemListResponse", "etag": "p4VTdlkQv3HQeTEaXgvLePAydmU/Vc3EkgLSTjYGqvhPMXul5T13c6k", "pageInfo": { "totalResults": 19, "resultsPerPage": 50 }, "items": [ { "kind": "youtube#playlistItem", "etag": "p4VTdlkQv3HQeTEaXgvLePAydmU/7hcDWTrN7EFhot4DpXw8fi97qUo", "id": "UExvQXI3RzlNaGtuOG1jTTR2VjE4SlY1RG5EMnJLQUYxNC5CMUM0NzY5NzdEQzlGRjAx", "snippet": { "publishedAt": "2019-12-23T17:23:10.000Z", "channelId": "UCaSq01bKPGAmrOnjpzBFDPQ", "title": "Regal - Repeat", "description": "Released by: Involve Records \n\nRelease/catalogue number: INV008 \n\nRelease date: Jun 15, 2015\n\nBuy and support\nhttp://decks.de/t/regal-alma_mater_ep/c55-r6\n\nhttp://facebook.com/RegalOfficial\nhttp://soundcloud.com/regalmusic\n\nhttp://involverecords.es\nhttp://facebook.com/involverecords\nhttp://soundcloud.com/involve-records\n\nRegal is back on his own imprint with a 4 cuts powerful EP. Two acid cuts, as couldn’t be otherwise, plus two dark, but full of soul, techno tracks for the mental moment of the night.\n\nAll rights reserved for the producers of these tracks.", "thumbnails": { "default": { "url": "https://i.ytimg.com/vi/7QPrJa7z12s/default.jpg", "width": 120, "height": 90 }, "medium": { "url": "https://i.ytimg.com/vi/7QPrJa7z12s/mqdefault.jpg", "width": 320, "height": 180 }, "high": { "url": "https://i.ytimg.com/vi/7QPrJa7z12s/hqdefault.jpg", "width": 480, "height": 360 }, "standard": { "url": "https://i.ytimg.com/vi/7QPrJa7z12s/sddefault.jpg", "width": 640, "height": 480 }, "maxres": { "url": "https://i.ytimg.com/vi/7QPrJa7z12s/maxresdefault.jpg", "width": 1280, "height": 720 } }, "channelTitle": "Channelxyz", "playlistId": "PLoAr7G9Mhkn8mcM4vV18JV5DnD2rKAF14", "position": 0, "resourceId": { "kind": "youtube#video", "videoId": "7QPrJa7z12s" } }, "contentDetails": { "videoId": "7QPrJa7z12s", "videoPublishedAt": "2015-07-02T15:07:27.000Z" } } ] }';
var str = str.jsonEscape();

var obj = JSON.parse(str, function (key, value) {
return value;
});
console.log(obj.etag);
// p4VTdlkQv3HQeTEaXgvLePAydmU/Vc3EkgLSTjYGqvhPMXul5T13c6k

Thanks for your help, James.

douglascrockford commented 4 years ago

It is not safe to add stuff to the system's prototypes. A better solution is to use JSON.stringify. Happy new year.

stephen147 commented 4 years ago

Thanks for the tip, Douglas. Happy new year to you also!