How to parse string contained json object with escape characters? - javascript
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".
Related
When formatting JSON using JavaScript I get an error because of the " (double quote) flag in the data
I using the following snippet, I'm legibly displaying all JSON strings in <pre> tag with id="jsonText" on the page. var p = document.querySelectorAll("#jsonText"); var parray = [...p] parray.forEach(p => { var data = p.textContent; p.textContent = JSON.stringify(JSON.parse(data), null, 2); }); However, I get an error when there are double quotes (") in the data. NOTE: The problematic field in the JSON is the "hardcore" part in the value of the "description" key. Error: jquery.min.js:2 Uncaught SyntaxError: Expected ',' or '}' after property value in JSON at position 289 at JSON.parse (<anonymous>) at getNews:152:33 at Array.forEach (<anonymous>) at HTMLDocument.<anonymous> (getNews:143:20) at e (jquery.min.js:2:30005) at t (jquery.min.js:2:30307) (anonymous) # getNews:152 (anonymous) # getNews:143 . . . I tried various RegEx methods to correct the double quotes, but these methods caused insertions where escape characters should not be inserted, or they did not work at all. This is the JSON text in <pre> tag. (The fields are being filled by Golang's Template.) <pre id="jsonText">{"guid": "{{.ID}}", "title": "{{.Title}}", "url": "{{.URL}}", "description": "{{.Description}}", "sourcename": "{{.SourceName}}", "sourceurl": "{{.SourceURL}}", "imageurl": "{{.ImageURL}}", "language": "{{.Language}}", "location": "{{.Location}}", "time": {{.Time}}, "tags": "{{.Tags}}", "type": {{.Type}}}</pre> I tried the Method 1: var escapedData = data.replace(/\"/g, "\\\""); console.log("Escaped JSON: ", escapedData); jsonData = JSON.parse(escapedData); p.textContent = JSON.stringify(jsonData, null, 2); console.log("Fixed JSON: ", p.textContent); NOTE: The problematic field in the JSON is the "hardcore" part in the value of the "description" key. Input: { "guid": "https://www.bbc.co.uk/news/business-63648505", "title": "Elon Musk tells Twitter staff to work long hours or leave", "url": "https://www.bbc.co.uk/news/business-63648505?at_medium=RSS&at_campaign=KARANGA", "description": "Elon Musk says workers at the social media firm must be "hardcore" if they want to stay, reports say.", "sourcename": "BBC", "sourceurl": "https://www.bbc.com/news", "imageurl": "https://www.bbc.com/news/special/2015/newsspec_10857/bbc_news_logo.png?cb=1", "language": "EN", "location": "UK", "time": 1668616715, "tags": "", "type": 2 } Output: Escaped JSON: {\"guid\": \"https://www.bbc.co.uk/news/business-63648505\", \"title\": \"Elon Musk tells Twitter staff to work long hours or leave\", \"url\": \"https://www.bbc.co.uk/news/business-63648505?at_medium=RSS&at_campaign=KARANGA\", \"description\": \"Elon Musk says workers at the social media firm must be \"hardcore\" if they want to stay, reports say.\", \"sourcename\": \"BBC\", \"sourceurl\": \"https://www.bbc.com/news\", \"imageurl\": \"https://www.bbc.com/news/special/2015/newsspec_10857/bbc_news_logo.png?cb=1\", \"language\": \"EN\", \"location\": \"UK\", \"time\": 1668616715, \"tags\": \"\", \"type\": 2} I tried Method 2: var escapedData = data.replace(/"([^"]+)"/g, function(match, capture) { return '"' + capture.replace(/"/g, "\\\"") + '"'; }); jsonData = JSON.parse(escapedData); p.textContent = JSON.stringify(jsonData, null, 2); console.log("Fixed JSON: ", p.textContent); The output was same as the input, at Method 2. All I want is that the JSON text look like this. Thanks in advance for your help.
Since you use a Goland template with Handlebars your JSON format will fail if the Description field contains quotes, as you describe. Your expanded string: "description": "Elon Musk says workers at the social media firm must be "hardcore" if they want to stay, reports say.", needs to be escaped to: "description": "Elon Musk says workers at the social media firm must be \"hardcore\" if they want to stay, reports say.", I am not familiar with Handlebars for Golang, but assuming it is compatible with regular Handlebars you can register a helper function to properly escape double quotes for use like: "description": "{{{escapeQuotes .Description}}}", Define the helper function to escape quotes as follows: Handlebars.registerHelper('escapeQuotes', function (aString) { return aString.replace(/"/g, '\\"'); }); You can try this out at the Handlebars playground at https://handlebarsjs.com/playground.html
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
Variable JSON values / methods inside JSON
My website has a functionality of synthesizing speech from preset text. I wanted to diversify it to include multiple languages. Hence, I chose to move the texts to JSON voiceOutputs. { "english": { "actionStarted": "Action has started", "success": "Success", "error": "Error occured", "goodNight": "Good Night" }, "japanese": { "actionStarted": "アクションが始まりました", "success": "成功しました", "error": "エラーが発生しました", "goodNight": "おやすみなさい" } } And I can use these texts by voiceOutputs.[getCookie("voiceLang")].actionStarted; How do I revamp my variable dependent texts into JSON structure as the sentence pattern differs with languages. Eg. "Good bye " + variableforName variableForName + "おやすみなさい。" I can't call "goodBye" and "おやすみなさい" directly as I want to create a generalized version of output and I need a proper word pattern depending on language. Work-arounds: 1. Using a function (easy but not optimized and takes a lot of work) function goodNight(variableForName) { if (getCookie("voiceLang") == "japanese") { return variableForName+voiceOutputs.[getCookie("voiceLang")].goodNight; } else if (getCookie("voiceLang") == "english") { return voiceOutputs.[getCookie("voiceLang")].goodNight + " " + variableForName; } Methods inside voiceOutputs JSON: Is it possible???
You can use a library for string formats (I do not know of any solid ones, please edit my answer or post your own), but you could also just use Vanilla Javascript's String.prototype.replace Combined with a character pattern you expect not to be seen in the same string otherwise E.g. "Good bye {{%name}}"; "{{%name}}おやすみなさい。"; You can then use both the same way, by calling .replace('{{%name}}', nameVariable)
Dealing with uint8_t in javascript
G'day peoples, I'm using MavLink to obtain GPS information. One of the message types is GPS_STATUS which is described by MavLink using a series of uint8_t[20]. If I run the following code: console.log(' sat prn: ' + message.satellite_prn); console.log(' sat prn: ' + JSON.stringify(message.satellite_prn)); console.log(' sat prn: ' + JSON.stringify(new Uint8Array(message.satellite_prn))); I get the following output: sat prn: <weird charcaters...> sat prn: "\u0002\u0005\n\f\u000f\u0012\u0015\u0019\u001a\u001b\u001d\u001e\u001f\u0000\u0000\u0000\u0000" sat prn: {"BYTES_PER_ELEMENT":1,"buffer":{"byteLength":0},"length":0,"byteOffset":0,"byteLength":0} So obviously it's not working. I need a means to get the int value of each element. I found this https://developer.mozilla.org/en-US/docs/JavaScript/Typed_arrays?redirectlocale=en-US&redirectslug=JavaScript_typed_arrays Which made me think I would be able to do the following: satellite_prn = Array.apply([], new Uint8Array(message.satellite_prn)); satellite_prn.length === 20; satellite_prn.constructor === Array; But when I stringify it via JSON it reports [], I presume this is an empty array. Anyone know how I can do this? I know that the data is an array of 20 unsigned 8 bit integers. I just need to know how to access or parse them. Note: I'm using node.js, but that shouldn't affect what I'm doing. This is why I'm using console.log, as it's avail in node.js.
Two issues with your code: message.satellite_prn is a string not an array Unit8Array needs to be loaded with .set To get an array of numbers from message.satellite_prn, do this: var array = message.satellite_prn.map(function(c) { return c.charCodeAt(0) }) To load an ArrayBuffer, do this: var buffer = new ArrayBuffer(array.length); var uint8View = new Uint8Array(buffer); uint8View.set(array); Ideally you wouldn't need to go through the string. If you are obtaining the data from an up-to-date implementation of XMLHttpRequest, such as xhr2, you can set: responseType = "arraybuffer"
Looks like the problem is my understanding on how to deal with binary data within javascript. I found that I can just do the following to get the data as base 10 via charCodeAt(). The following is the code that allowed me to iterate through the 20 unsigned 8 bit integers and get each value as a decimal: for(var i = 0, l = message.satellite_prn.length; i < l; i++) { console.log(' Satellite ' + i + ', id: ' + parseInt(message.satellite_prn.charCodeAt(i), 10) ); } I suspect that there may be a function that allows me to convert the binary data into an array, but for an unknown reason Uint8Array didn't appear to be working for me. However the above does.
How to check the size of a JSON response?
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; }