JSON.parse嵌套的JSON字符串属性解析 [英] JSON.parse nested JSON string property parsing

查看:313
本文介绍了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.

这篇关于JSON.parse嵌套的JSON字符串属性解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆