JSON.parse嵌套的JSON字符串属性解析

问题描述:

我从API模块获取以下字符串:

I am getting the following string from an API module:

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

当我在客户端使用JSON.parse时,我得到:

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

Uncaught SyntaxError: Unexpected token I in JSON at position 12

如果里面的引号是双转义的,这是可行的,但是什么是最好的方法呢?更具体地说,这是由Ionic Capacitor插件从本机代码返回到JavaScript环境返回的.

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.