How to check the size of a JSON response? - javascript

Is there any way I can check the response size? Data property is a byte array which I am using to display an image. If the size is greater than 10 MB I need to show a popup.
{
"Name": "sharon",
"Date": "07\/14\/2004",
"Data": "JVBERi0xLjINCg0KNC",
"DocumentId":1540,
}
Also how can I check the type of my response, whether it's blob or something? Can I check the size of the blob I am getting? Maybe something like this:
var data = JSON.parse(this.responseData);

You simply can use JavaScript .length for this, but do realize different browsers as well as servers will report different values since some interpretation of newlines can be 1 of 2 size values (byte-order).
Having said that, use a "loose" value that your sure contains the data you need, and not just the header response that has no value.

You can slurp the incoming response into one line and remove all unnecessary white-space.
var JSON = '{\r\n' +
' "Name": "sharon",\r\n' +
' "Date": "07\/14\/2004",\r\n' +
' "Data": "JVBERi0xLjINCg0KNC",\r\n' +
' "DocumentId":1540,\r\n' +
'}';
alert(JSON);
alert(JSON.length); // 101
var newJSON = slurp(JSON);
alert(newJSON);
alert(newJSON.length); // 91
function slurp(str) {
str = str.replace(/(\r\n|\n|\r)/gm,"");
str = str.replace(/(\s+|\t)/gm,' ');
return str;
}

Related

JSON Parse not working, parsing two dimensional array

I am trying to parse this LOCAL XMLhttprequest, I am getting back the right response text and displaying it in safari.
When I make an object to JSON.parse() the responsetext,I am getting errors like "unidentified token '"' " or "expected '}' " no matter how I change the .txt file, it will not parse into an object for me
I have tried to change the .txt to the right JSON format with no luck
{playerGrid: [["3","2","2","2","2","2","2","3","3","3"], ["3","2","2","2","2","2","2","2","2","2"], ["3","2","2","2","2","2","2","2","2","3"],["3","2","2","2","2","2","2","2","2","3"], ["4","2","2","2","2","3","2","2","2","3"], ["2","2","2","2","7","3","2","2","2","3"], ["2","2","2","2","7","2","2","2","2","2"], ["2","2","2","3","3","3","2","2","2","2"], ["2","2","2,"2","2","2","2","2","2","2"], ["2","2","2","2","2","2","2","2","2","2"]],
computerGrid: [["2","2","2","7","4","9","9","2","2","2"], ["2","9","2","2","2","2","2","2","2","2"], ["2","9","2","2","2","2","2","2","2","2"], ["2","9","2","2","9","9","2","2,"2","2"], ["2","2","2","2","2","2","2","2","2","2"], ["9","9","9","9","9","2","2","2","2","2"], ["2","2","2","2","7","2","2","2","9","2"], ["2","2","2","2","2","2","2","2","9","2"], ["2","2","2","2","2","2","2","2","9","2"], ["2","2","2","2","2","2","2","2","9","2"]]};
here is my JOSN .txt
function fileRequest()
{
var localRequest = new XMLHttpRequest();
localRequest.open("GET", "sampleJSON.txt", false);
localRequest.send(null);
document.getElementById("jsonDiv").innerHTML = localRequest.responseText;
var jsonObject = JSON.parse(localRequest.response);
document.getElementById("jsonParsed").innerHTML = jsonObject.computerGrid;
}
here is my simple function, I first display the response, and then it errors when I am trying to parse the data.
Thanks
I expect an object that I can .computerGrid or .playerGrid.
You have some errors in your json, just search by "2,, there are 2 occurences, it should be "2",.
You are missing a closing ".
Also, in order to the JSON to be valid, it should look like this:
{"playerGrid":[["3","2","2","2","2","2","2","3","3","3"],["3","2","2","2","2","2","2","2","2","2"],["3","2","2","2","2","2","2","2","2","3"],["3","2","2","2","2","2","2","2","2","3"],["4","2","2","2","2","3","2","2","2","3"],["2","2","2","2","7","3","2","2","2","3"],["2","2","2","2","7","2","2","2","2","2"],["2","2","2","3","3","3","2","2","2","2"],["2","2","2","2","2","2","2","2","2","2"],["2","2","2","2","2","2","2","2","2","2"]],"computerGrid":[["2","2","2","7","4","9","9","2","2","2"],["2","9","2","2","2","2","2","2","2","2"],["2","9","2","2","2","2","2","2","2","2"],["2","9","2","2","9","9","2","2","2","2"],["2","2","2","2","2","2","2","2","2","2"],["9","9","9","9","9","2","2","2","2","2"],["2","2","2","2","7","2","2","2","9","2"],["2","2","2","2","2","2","2","2","9","2"],["2","2","2","2","2","2","2","2","9","2"],["2","2","2","2","2","2","2","2","9","2"]]}
Keys, playerGrid and computerGrid must be between ".
Use JSON.parse(localRequest.responseText)
Your JSON is incorrect, you are missing quotes around some numbers like "2,
Object Keys "playerGrid" and "computerGrid" must be quoted too
let d = `{
"playerGrid": [
["3","2","2","2","2","2","2","3","3","3"], ["3","2","2","2","2","2","2","2","2","2"],
["3","2","2","2","2","2","2","2","2","3"], ["3","2","2","2","2","2","2","2","2","3"],
["4","2","2","2","2","3","2","2","2","3"], ["2","2","2","2","7","3","2","2","2","3"],
["2","2","2","2","7","2","2","2","2","2"], ["2","2","2","3","3","3","2","2","2","2"],
["2","2","2","2","2","2","2","2","2","2"], ["2","2","2","2","2","2","2","2","2","2"]],
"computerGrid": [
["2","2","2","7","4","9","9","2","2","2"], ["2","9","2","2","2","2","2","2","2","2"],
["2","9","2","2","2","2","2","2","2","2"], ["2","9","2","2","9","9","2","2","2","2"],
["2","2","2","2","2","2","2","2","2","2"], ["9","9","9","9","9","2","2","2","2","2"],
["2","2","2","2","7","2","2","2","9","2"], ["2","2","2","2","2","2","2","2","9","2"],
["2","2","2","2","2","2","2","2","9","2"], ["2","2","2","2","2","2","2","2","9","2"]]
}`;
console.log(JSON.parse(d))
PS: you can always validate your json with codebeautify.org/jsonvalidator

How to parse string contained json object with escape characters?

I can't parse this following string with JSON.parse() function.
At first I tried to remove the initial and final double quotes. And then I removed the escape characters.
How to parse this type of JSON response?
{
"timestamp": 1490545425158,
"reports": {
"statusCode": 200,
"body": "{\"responseCode\":\"200\",\"responseMessage\":\"Success\",\"getevent\":[{\"eventID\":\"24844563\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-25 16:00:00.0\",\"displayDateTime\":\"2017-03-26 00:00:00.0\",\"displayDuration\":\"06:00:00\",\"siTrafficKey\":\"1:2169:30291203\",\"programmeTitle\":\"Great Golden Oldies\",\"programmeId\":\"GBSSJ\",\"episodeId\":\"\",\"shortSynopsis\":\"Mixture of '50s to '70s songs.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844564\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-25 22:00:00.0\",\"displayDateTime\":\"2017-03-26 06:00:00.0\",\"displayDuration\":\"04:00:00\",\"siTrafficKey\":\"1:2169:30291204\",\"programmeTitle\":\"Breakfast Time\",\"programmeId\":\"GBSSK\",\"episodeId\":\"\",\"shortSynopsis\":\"Wake up to Golden Oldies.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844565\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-26 02:00:00.0\",\"displayDateTime\":\"2017-03-26 10:00:00.0\",\"displayDuration\":\"02:00:00\",\"siTrafficKey\":\"1:2169:30291205\",\"programmeTitle\":\"The Best Mix\",\"programmeId\":\"GBSSE\",\"episodeId\":\"\",\"shortSynopsis\":\"Best songs for the day.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844566\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-26 04:00:00.0\",\"displayDateTime\":\"2017-03-26 12:00:00.0\",\"displayDuration\":\"03:00:00\",\"siTrafficKey\":\"1:2169:30291206\",\"programmeTitle\":\"Lunch Time with Oldies\",\"programmeId\":\"GBSSH\",\"episodeId\":\"\",\"shortSynopsis\":\"Mixture of '50s to '70s songs.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844567\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-26 07:00:00.0\",\"displayDateTime\":\"2017-03-26 15:00:00.0\",\"displayDuration\":\"03:00:00\",\"siTrafficKey\":\"1:2169:30291207\",\"programmeTitle\":\"Your Favourites\",\"programmeId\":\"GBSSD\",\"episodeId\":\"\",\"shortSynopsis\":\"Giving you the songs you grew up with.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844568\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-26 10:00:00.0\",\"displayDateTime\":\"2017-03-26 18:00:00.0\",\"displayDuration\":\"06:00:00\",\"siTrafficKey\":\"1:2169:30291208\",\"programmeTitle\":\"Starry Night\",\"programmeId\":\"GBSSF\",\"episodeId\":\"\",\"shortSynopsis\":\"More of the golden songs.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]}]}"
}
}
Assuming it's really a string (e.g., from a network request or similar), you use JSON.parse on it. Then, since the body property is a string containing JSON (e.g., its contents have been double-stringified for some reason), you parse that again.
Example:
var json = '{\n' +
' "timestamp": 1490545425158,\n' +
' "reports": {\n' +
' "statusCode": 200,\n' +
' "body": "{\\"responseCode\\":\\"200\\",\\"responseMessage\\":\\"Success\\",\\"getevent\\":[{\\"eventID\\":\\"24844563\\",\\"channelId\\":21,\\"channelStbNumber\\":\\"861\\",\\"channelHD\\":\\"false\\",\\"channelTitle\\":\\"Gold\\",\\"epgEventImage\\":null,\\"certification\\":\\"U\\",\\"displayDateTimeUtc\\":\\"2017-03-25 16:00:00.0\\",\\"displayDateTime\\":\\"2017-03-26 00:00:00.0\\",\\"displayDuration\\":\\"06:00:00\\",\\"siTrafficKey\\":\\"1:2169:30291203\\",\\"programmeTitle\\":\\"Great Golden Oldies\\",\\"programmeId\\":\\"GBSSJ\\",\\"episodeId\\":\\"\\",\\"shortSynopsis\\":\\"Mixture of \'50s to \'70s songs.\\",\\"longSynopsis\\":null,\\"actors\\":\\"\\",\\"directors\\":\\"\\",\\"producers\\":\\"\\",\\"genre\\":\\"Music & Dance\\",\\"subGenre\\":\\"General\\",\\"live\\":false,\\"premier\\":false,\\"ottBlackout\\":false,\\"highlight\\":null,\\"contentId\\":null,\\"contentImage\\":null,\\"groupKey\\":null,\\"vernacularData\\":[]},{\\"eventID\\":\\"24844564\\",\\"channelId\\":21,\\"channelStbNumber\\":\\"861\\",\\"channelHD\\":\\"false\\",\\"channelTitle\\":\\"Gold\\",\\"epgEventImage\\":null,\\"certification\\":\\"U\\",\\"displayDateTimeUtc\\":\\"2017-03-25 22:00:00.0\\",\\"displayDateTime\\":\\"2017-03-26 06:00:00.0\\",\\"displayDuration\\":\\"04:00:00\\",\\"siTrafficKey\\":\\"1:2169:30291204\\",\\"programmeTitle\\":\\"Breakfast Time\\",\\"programmeId\\":\\"GBSSK\\",\\"episodeId\\":\\"\\",\\"shortSynopsis\\":\\"Wake up to Golden Oldies.\\",\\"longSynopsis\\":null,\\"actors\\":\\"\\",\\"directors\\":\\"\\",\\"producers\\":\\"\\",\\"genre\\":\\"Music & Dance\\",\\"subGenre\\":\\"General\\",\\"live\\":false,\\"premier\\":false,\\"ottBlackout\\":false,\\"highlight\\":null,\\"contentId\\":null,\\"contentImage\\":null,\\"groupKey\\":null,\\"vernacularData\\":[]},{\\"eventID\\":\\"24844565\\",\\"channelId\\":21,\\"channelStbNumber\\":\\"861\\",\\"channelHD\\":\\"false\\",\\"channelTitle\\":\\"Gold\\",\\"epgEventImage\\":null,\\"certification\\":\\"U\\",\\"displayDateTimeUtc\\":\\"2017-03-26 02:00:00.0\\",\\"displayDateTime\\":\\"2017-03-26 10:00:00.0\\",\\"displayDuration\\":\\"02:00:00\\",\\"siTrafficKey\\":\\"1:2169:30291205\\",\\"programmeTitle\\":\\"The Best Mix\\",\\"programmeId\\":\\"GBSSE\\",\\"episodeId\\":\\"\\",\\"shortSynopsis\\":\\"Best songs for the day.\\",\\"longSynopsis\\":null,\\"actors\\":\\"\\",\\"directors\\":\\"\\",\\"producers\\":\\"\\",\\"genre\\":\\"Music & Dance\\",\\"subGenre\\":\\"General\\",\\"live\\":false,\\"premier\\":false,\\"ottBlackout\\":false,\\"highlight\\":null,\\"contentId\\":null,\\"contentImage\\":null,\\"groupKey\\":null,\\"vernacularData\\":[]},{\\"eventID\\":\\"24844566\\",\\"channelId\\":21,\\"channelStbNumber\\":\\"861\\",\\"channelHD\\":\\"false\\",\\"channelTitle\\":\\"Gold\\",\\"epgEventImage\\":null,\\"certification\\":\\"U\\",\\"displayDateTimeUtc\\":\\"2017-03-26 04:00:00.0\\",\\"displayDateTime\\":\\"2017-03-26 12:00:00.0\\",\\"displayDuration\\":\\"03:00:00\\",\\"siTrafficKey\\":\\"1:2169:30291206\\",\\"programmeTitle\\":\\"Lunch Time with Oldies\\",\\"programmeId\\":\\"GBSSH\\",\\"episodeId\\":\\"\\",\\"shortSynopsis\\":\\"Mixture of \'50s to \'70s songs.\\",\\"longSynopsis\\":null,\\"actors\\":\\"\\",\\"directors\\":\\"\\",\\"producers\\":\\"\\",\\"genre\\":\\"Music & Dance\\",\\"subGenre\\":\\"General\\",\\"live\\":false,\\"premier\\":false,\\"ottBlackout\\":false,\\"highlight\\":null,\\"contentId\\":null,\\"contentImage\\":null,\\"groupKey\\":null,\\"vernacularData\\":[]},{\\"eventID\\":\\"24844567\\",\\"channelId\\":21,\\"channelStbNumber\\":\\"861\\",\\"channelHD\\":\\"false\\",\\"channelTitle\\":\\"Gold\\",\\"epgEventImage\\":null,\\"certification\\":\\"U\\",\\"displayDateTimeUtc\\":\\"2017-03-26 07:00:00.0\\",\\"displayDateTime\\":\\"2017-03-26 15:00:00.0\\",\\"displayDuration\\":\\"03:00:00\\",\\"siTrafficKey\\":\\"1:2169:30291207\\",\\"programmeTitle\\":\\"Your Favourites\\",\\"programmeId\\":\\"GBSSD\\",\\"episodeId\\":\\"\\",\\"shortSynopsis\\":\\"Giving you the songs you grew up with.\\",\\"longSynopsis\\":null,\\"actors\\":\\"\\",\\"directors\\":\\"\\",\\"producers\\":\\"\\",\\"genre\\":\\"Music & Dance\\",\\"subGenre\\":\\"General\\",\\"live\\":false,\\"premier\\":false,\\"ottBlackout\\":false,\\"highlight\\":null,\\"contentId\\":null,\\"contentImage\\":null,\\"groupKey\\":null,\\"vernacularData\\":[]},{\\"eventID\\":\\"24844568\\",\\"channelId\\":21,\\"channelStbNumber\\":\\"861\\",\\"channelHD\\":\\"false\\",\\"channelTitle\\":\\"Gold\\",\\"epgEventImage\\":null,\\"certification\\":\\"U\\",\\"displayDateTimeUtc\\":\\"2017-03-26 10:00:00.0\\",\\"displayDateTime\\":\\"2017-03-26 18:00:00.0\\",\\"displayDuration\\":\\"06:00:00\\",\\"siTrafficKey\\":\\"1:2169:30291208\\",\\"programmeTitle\\":\\"Starry Night\\",\\"programmeId\\":\\"GBSSF\\",\\"episodeId\\":\\"\\",\\"shortSynopsis\\":\\"More of the golden songs.\\",\\"longSynopsis\\":null,\\"actors\\":\\"\\",\\"directors\\":\\"\\",\\"producers\\":\\"\\",\\"genre\\":\\"Music & Dance\\",\\"subGenre\\":\\"General\\",\\"live\\":false,\\"premier\\":false,\\"ottBlackout\\":false,\\"highlight\\":null,\\"contentId\\":null,\\"contentImage\\":null,\\"groupKey\\":null,\\"vernacularData\\":[]}]}"\n' +
' }\n' +
'}';
var parsed = JSON.parse(json);
parsed.reports.body = JSON.parse(parsed.reports.body); // This is the second parse
console.log(parsed);
But: Ideally, you'd want to fix the source which is unnecessarily double-stringifying body.
Of course, if something's already done the first parse for you (for instance, many libraries will automatically parse JSON retrieved via ajax), then of course you don't need that first parse:
var parsed = {
"timestamp": 1490545425158,
"reports": {
"statusCode": 200,
"body": "{\"responseCode\":\"200\",\"responseMessage\":\"Success\",\"getevent\":[{\"eventID\":\"24844563\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-25 16:00:00.0\",\"displayDateTime\":\"2017-03-26 00:00:00.0\",\"displayDuration\":\"06:00:00\",\"siTrafficKey\":\"1:2169:30291203\",\"programmeTitle\":\"Great Golden Oldies\",\"programmeId\":\"GBSSJ\",\"episodeId\":\"\",\"shortSynopsis\":\"Mixture of '50s to '70s songs.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844564\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-25 22:00:00.0\",\"displayDateTime\":\"2017-03-26 06:00:00.0\",\"displayDuration\":\"04:00:00\",\"siTrafficKey\":\"1:2169:30291204\",\"programmeTitle\":\"Breakfast Time\",\"programmeId\":\"GBSSK\",\"episodeId\":\"\",\"shortSynopsis\":\"Wake up to Golden Oldies.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844565\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-26 02:00:00.0\",\"displayDateTime\":\"2017-03-26 10:00:00.0\",\"displayDuration\":\"02:00:00\",\"siTrafficKey\":\"1:2169:30291205\",\"programmeTitle\":\"The Best Mix\",\"programmeId\":\"GBSSE\",\"episodeId\":\"\",\"shortSynopsis\":\"Best songs for the day.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844566\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-26 04:00:00.0\",\"displayDateTime\":\"2017-03-26 12:00:00.0\",\"displayDuration\":\"03:00:00\",\"siTrafficKey\":\"1:2169:30291206\",\"programmeTitle\":\"Lunch Time with Oldies\",\"programmeId\":\"GBSSH\",\"episodeId\":\"\",\"shortSynopsis\":\"Mixture of '50s to '70s songs.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844567\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-26 07:00:00.0\",\"displayDateTime\":\"2017-03-26 15:00:00.0\",\"displayDuration\":\"03:00:00\",\"siTrafficKey\":\"1:2169:30291207\",\"programmeTitle\":\"Your Favourites\",\"programmeId\":\"GBSSD\",\"episodeId\":\"\",\"shortSynopsis\":\"Giving you the songs you grew up with.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844568\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-26 10:00:00.0\",\"displayDateTime\":\"2017-03-26 18:00:00.0\",\"displayDuration\":\"06:00:00\",\"siTrafficKey\":\"1:2169:30291208\",\"programmeTitle\":\"Starry Night\",\"programmeId\":\"GBSSF\",\"episodeId\":\"\",\"shortSynopsis\":\"More of the golden songs.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]}]}"
}
};
parsed.reports.body = JSON.parse(parsed.reports.body); // Parse body
console.log(parsed);
You need to parse the body:
JSON.parse(object.reports.body)
The rest is already "parsed".

Unexpected token o in JSON at position 1

I keep getting this error in this block of code below:
function openWebsocket(url) {
var ws;
ws = $websocket(url);
ws.onOpen(function(event) {
console.log(' Websocket connection established:', event);
});
ws.onMessage(function(message) {
var userObj = UserFactory.getUserObject();
var settings = userObj.alert_settings;
// The JSON parsing...
var parsedMsg = JSON.parse(message.data);
var alert = JSON.parse(parsedMsg);
var date = new Date(parseFloat(alert.start_epoch+'000'));
alert.hour = date.getHours() +':'+date.getMinutes();
alert.percent_change = Math.round(alert.percent_change);
var shouldPush = main_alert_filter(settings, alert);
updateFeed(alerts, shouldPush, alert);
});
}
I've looked at both Parsing JSON giving "unexpected token o" error and I keep getting "Uncaught SyntaxError: Unexpected token o"
However neither answer helped. Because when I first run JSON.parse(message.data) I get a string back not an Object. So thus I have to run JSON.parse again to finally get a real object back.
This is what message.data looks like:
"
"{\"term\": \"\\\"nike\\\"\", \"percent_change\": 125, \"hour\": \"10:9\", \"term_id\": 2890413, \"start_epoch\": 1420474140, \"term_trend_id\": 793950, \"end_epoch\": 1420477740, \"formatted_date_difference\": \"January 5, 2015\", \"tickers\": [\"NKE\", \"$PUM\", \"ADDYY\", \"LULU\", \"UA\", \"HIBB\"], \"twitter_preview\": \"\", \"type\": \"spike\", \"approved\": 1, \"search_preview\": [\"\"]}"
"
Now after the first parsing parsedMsg is a string that looks like this:
{"term": "minimum wage +increase", "percent_change": 729, "hour": "9:14", "term_id": 2522115, "start_epoch": 1447168440, "term_trend_id": 657898, "end_epoch": 1447175700, "formatted_date_difference": "November 10, 2015", "tickers": ["$JAB", "$SLCY", "AAL", "AAPL", "ABCD", "ABTL", "ADDYY", "ADM", "AEO", "AFCO", "AHC"......
Finally I need an actual object, so I have to run JSON.parse again to get this:
Object {term: "minimum wage +increase", percent_change: 729, hour: "9:14", term_id: 2522115, start_epoch: 1447168440…}
Another thing to note, I never get that error when I'm stepping through in Chrome. It only happens when I don't have the breakpoint set. Could this be a race condition type issue? Like it tries to JSON.parse something that isn't ready to be parsed?
UPDATE
Ok so sometimes the JSON is invalid apparently and sometimes not, so far I'm doing good without errors with the following snippet, thoughts?
if (typeof alert === 'object') {
// do nothing...
} else {
var alert = JSON.parse(alert);
}
Most of the time the alert result of JSON.parse(message.data) is a string so I need the other check to double parse it.
Why would you parse your json second time, its already been parsed in the first attempt.
Have a look at the snippet
var obj = "{\"term\": \"minimum wage +increase\", \"percent_change\": 729, \"hour\": \"9:14\", \"term_id\": 2522115, \"start_epoch\": 1447168440, \"term_trend_id\": 657898, \"end_epoch\": 1447175700, \"formatted_date_difference\": \"November 10, 2015\", \"tickers\": [\"$JAB\", \"$SLCY\", \"AAL\", \"AAPL\", \"ABCD\", \"ABTL\", \"ADDYY\"]}";
$(function(){
var data = JSON.parse(obj);
alert(typeof data);
console.log(data.tickers[0] +" -> an item in `tickers` array");
console.log(data.tickers);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The JSON string you specified with message.data is not a well formed JSON parsed as String. It might be because the server is sending you a multi-part message during/after establishing the connection.
I suggest you print the message object received in OnMessage function and analyze if they are fully formed valid JSON Strings.
It looks like Your message.data is incomplete.
Take a look on the library docs You are using, maybe you should collect the data until it's end? Maybe there is some onEnd method?

How to customize JSON output on the first level ONLY using JavaScript's stringify() method?

I use stringify() method in JavaScript to convert a list of objects to a string, but I need to customize the output on the first level ONLY like the following:
[
/*T01*/ {"startX":55,"endX":109,"sartY":0,"endY":249},
/*T02*/ {"startX":110,"endX":164,"sartY":0,"endY":249},
/*T03*/ {"startX":165,"endX":219,"sartY":0,"endY":249},
/*T04*/ {"startX":220,"endX":274,"sartY":0,"endY":249},
/*T05*/ {"startX":275,"endX":329,"sartY":0,"endY":249},
/*T06*/ {"startX":330,"endX":384,"sartY":0,"endY":249},
/*T07*/ {"startX":385,"endX":439,"sartY":0,"endY":249},
/*T08*/ {"startX":440,"endX":494,"sartY":0,"endY":249},
/*T09*/ {"startX":495,"endX":549,"sartY":0,"endY":249},
/*T10*/ {"startX":550,"endX":604,"sartY":0,"endY":249}
]
Now there are other parameters in stringfy() method, replacer and space, can't I use them to format my output like the aforementioned format including:
tabs
spaces
comments
You are not going to get JSON.parse to make that output since it is not valid JSON. But if you want to have something rendered like that, it is a simple loop and string concatenation.
var details = [
{"startX":55,"endX":109,"sartY":0,"endY":249},
{"startX":110,"endX":164,"sartY":0,"endY":249},
{"startX":165,"endX":219,"sartY":0,"endY":249},
{"startX":220,"endX":274,"sartY":0,"endY":249},
{"startX":275,"endX":329,"sartY":0,"endY":249},
{"startX":330,"endX":384,"sartY":0,"endY":249},
{"startX":385,"endX":439,"sartY":0,"endY":249},
{"startX":440,"endX":494,"sartY":0,"endY":249},
{"startX":495,"endX":549,"sartY":0,"endY":249},
{"startX":550,"endX":604,"sartY":0,"endY":249}
];
var out = "[\n" + details.map(function(val, i) {
var id = "\t/*T" + ("0" + (i + 1)).substr(-2) + "*/\t";
return id + JSON.stringify(val);
}).join(",\n") + "\n]";
console.log(out);

javascript - simple arithmetic in creating dictionary

I'm using jQuery with Django to do some stuff with tables. I have the following javascript:
$("#pending_table").tablesorter({
headers: {5 + {{somevariable}}: {sorter:false},6 + {{somevariable}}: {sorter:false}}
});
(I omitted a bunch of other options that are irrelevant)
The part that's causing trouble is the addition in the headers dictionary definition. Looking at the source of the resulting webpage, I can see that {{somevariable}} converts properly to its value of 4, so it's not a Django-related issue.
In summary: "5 + 4 : value" does not work, "9 : value" does work.
I'm assuming I'm getting the syntax of the javascript wrong somehow.
Help?
Javascript object literals only allows literals as keys. In other words, you cannot have a calculated expression as a key. For example, this is unallowed:
headers = {
(1 + 2): 4
}
That said, you can do this to circumvent that restriction:
headers = {};
headers[1 + 2] = 4;
In your case, it looks like you want to do something like this:
var headers = {};
headers[5 + someVar] = {sorter: false};
headers[6 + someVar] = {sorter: false};
$("#pending_table").tablesorter({
headers: headers
});

Categories