JSON.parse nested JSON string property parsing

Viewed 871

I am getting the following string from an API module:

{"value":"{\"Id\":\"100\",\"OrganizationName\":\"[_+-:|;'.\\\/] Arizona 
Grower Automation\"}"}

When I use JSON.parse on the client side, I get:

Uncaught SyntaxError: Unexpected token I in JSON at position 12

This works if the quotes inside are double escaped, but whats the best way to do this ? More specifically this is returned by an Ionic Capacitor plugin from the native code to JavaScript environment.

1 Answers

You need to escape backslash as well as double quotes:

/// NO!
JSON.parse('{"value":"{\"Id\":\"100\",\"OrganizationName\":\"[_+-:|;\'.\\\/] Arizona Grower Automation\"}"}');
/// Syntax Error: Unexpected token I in JSON at position 12


/// YES!
JSON.parse('{"value":"{\\\"Id\\\":\\\"100\\\",\\\"OrganizationName\\\":\\\"[_+-:|;\'.\\\/] Arizona Grower Automation\\\"}"}');
/// value: "{"Id":"100","OrganizationName":"[_+-:|;'./] Arizona Grower Automation"}"

We need three backslashes because the first two represent a single backslash escaped, the third is the escape char for the double quotes.

Related