Skip to content Skip to sidebar Skip to footer

Handling Backslash When Parsing Json

Here is a portion of a larger JSON string that I attempting to call JSON.parse on. I am getting the infamous 'invalid character' error because (I believe) of the backslash parenth

Solution 1:

The problem is that your backslash is getting swallowed as an escape character in the string:

'\"' === '"' // true

You actually need to escape the backslashes, so that the JSON parser sees them. Here's another example:

var unencoded = 'string with "quotes"';

'"string with \"quotes\""'   ===JSON.stringify(unencoded); // false
'"string with \\"quotes\\""' ===JSON.stringify(unencoded); // true

However, where the escaping should be done depends on how the JSON is being made available to the JavaScript. If the JSON is embedded in the page by a server-side script, then there's no need to use JSON.parse, as valid JSON is valid JavaScript:

// if JsonData is valid JSON, it's also a valid JavaScript objectvardata = <%= JsonData %>; 

Post a Comment for "Handling Backslash When Parsing Json"