下面是我正在使用的一些JSON的示例:
{"name":"John","attributes":"{\"key\":\"value\"}"}这也是一种更易读的格式:
{
"name": "John",
"attributes": "{\"key\":\"value\"}"
}请注意,围绕键和值的双引号是转义的。这是必要的,并且是有效的JSON (在jsonlint.com上检查)。
我正在尝试获取"name“的值,但是转义的双引号会导致错误。
我的node.js代码做错了什么?
var theString = '{"name":"John","attributes":"{\"key\":\"value\"}"}';
var theJSON = JSON.parse(theString);
var theName = theJSON.name;
console.log("name = " + theName);下面是输出。错误发生在代码的第2行,其中我的字符串是"JSON.parse()“。JSON.parse似乎正在删除反斜杠,将有效的JSON转换为无效的JSON。
undefined:1
{"name":"John","attributes":"{"key":"value"}"}
^
SyntaxError: Unexpected token k in JSON at position 31发布于 2020-11-17 13:28:11
由于数据的这一部分是JSON,所以您需要解析JSON,然后在attributes属性上解析JSON:
const obj = JSON.parse(json);
obj.attributes = JSON.parse(obj.attributes);活生生的例子:
const json = document.getElementById("json").textContent;
const obj = JSON.parse(json);
obj.attributes = JSON.parse(obj.attributes);
console.log(obj);<pre id="json">{
"name": "John",
"attributes": "{\"key\":\"value\"}"
}</pre>
https://stackoverflow.com/questions/64876114
复制相似问题