JSON.parse nested JSON string property parsing

戏子无情 提交于 2020-01-04 08:27:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!