Javascript 将JSON.stringify字符串输出并复制到JSON.parse中,它会给出意外的标记';JSON格式
我从Javascript 将JSON.stringify字符串输出并复制到JSON.parse中,它会给出意外的标记';JSON格式,javascript,Javascript,我从console.log(JSON.stringify(employee);)获取并复制了字符串输出,并将其粘贴到parse()中,但失败了: //For the below I get Error: Unexpected token ' in JSON at position 1 const person = JSON.parse("{'id':0,'firstName':'Andy','subordinates':[{'id':1,'firstName':'James','subordin
console.log(JSON.stringify(employee);)
获取并复制了字符串输出,并将其粘贴到parse()中,但失败了:
//For the below I get Error: Unexpected token ' in JSON at position 1
const person = JSON.parse("{'id':0,'firstName':'Andy','subordinates':[{'id':1,'firstName':'James','subordinates':[{'id':3,'firstName':'Aubrey','subordinates':null}]},{'id':2,'firstName':'Collin','subordinates':null}]}");
但是,这确实有效:
我有点困惑为什么第一个失败了
const employee = {
id: 0,
firstName: "Andy",
subordinates: [
{
id: 1,
firstName: "James",
subordinates: [
{
id: 3,
firstName: "Aubrey",
subordinates: null
}
]
},
{
id: 2,
firstName: "Collin",
subordinates: null
}
]
};
您可以这样使用:
const person = JSON.parse('{"id":0,"firstName":"Andy","subordinates":[{"id":1,"firstName":"James","subordinates":[{"id":3,"firstName":"Aubrey","subordinates":null}]},{"id":2,"firstName":"Collin","subordinates":null}]}');
或者,如果您不想更改json数据,可以使用:
let json_data = "{'id':0,'firstName':'Andy','subordinates':[{'id':1,'firstName':'James','subordinates':[{'id':3,'firstName':'Aubrey','subordinates':null}]},{'id':2,'firstName':'Collin','subordinates':null}]}";
json_data = json_data.replace(/'/g, '"');
const person = JSON.parse(json_data);
希望本主题对您有所帮助。JSON使用双引号,而不是单引号。可能是您的浏览器在使用
console.log
“{'id':0,'firstName':'Andy','sub…这不能是JSON.stringify()的输出,它不是有效的JSON。”我从console.log(JSON.stringify(employee);)获取并复制了字符串输出,然后将其粘贴到“不,你没有。我只是尝试了JSON.stringify()你的对象,我得到了{“id”:0,“firstName”:“Andy”,“subordin…”所以你在骗我们:PI在codepen.ioright中做了stringify的console.log。我只是很惊讶,在我将stringify值设置为常量后,我可以传入stringify值:const rawData=JSON.stringify(employee);const person=JSON.parse(rawData)
但在中复制不起作用。我不想手动替换couse的东西,我只是尝试了一下
let json_data = "{'id':0,'firstName':'Andy','subordinates':[{'id':1,'firstName':'James','subordinates':[{'id':3,'firstName':'Aubrey','subordinates':null}]},{'id':2,'firstName':'Collin','subordinates':null}]}";
json_data = json_data.replace(/'/g, '"');
const person = JSON.parse(json_data);