【发布时间】:2021-02-28 17:16:29
【问题描述】:
这是我正在使用的一些 JSON 的示例:
{"name":"John","attributes":"{\"key\":\"value\"}"}
又来了,格式更易读:
{
"name": "John",
"attributes": "{\"key\":\"value\"}"
}
请注意,key 和 value 周围的双引号已转义。这是必要的,并且是有效的 JSON(在 jsonlint.com 上查看)。
我正在尝试获取“名称”的值,但转义的双引号导致错误。
我在 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
【问题讨论】:
标签: node.js json parsing escaping double-quotes