问题
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:
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.
来源:https://stackoverflow.com/questions/53013560/json-parse-nested-json-string-property-parsing