简体   繁体   中英

JSON.parse nested JSON string property parsing

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM