![](/img/trans.png)
[英]JSON.parse give me an error but JSONLint say it's a valid json
[英]Valid JSON in jsonlint, but JSON.parse() not working
我有一个在 JSONlint 中验证过的 JSON,但我不能使用 JSON.parse(),因为它不起作用。 这里的 JSON 有什么问题,如果不能使用 JSON.prase() 我有什么选择。
JSON string: "{Products: [{Id: 1,Increment: 5,Max: 1000,Min: 25,allowed: false,Desc: product description,Name:Product Name,Qty: 0}]}"
为了使JSON有效,您的对象键必须在双引号内:
{ "validKey": 123 }
^ ^
| |
------------- These double-quotes are required!
JSONLint表示没问题,因为您在粘贴此处时粘贴了JSON,并用引号引起来:
"{Products: [{Id: 1,Increment: 5,Max: 1000,Min: 25,allowed: false,Desc: product description,Name:Product Name,Qty: 0}]}"
这是一个内部带有JSON的JSON字符串,而不是JSON!
如果您尝试使用不带引号的JSONLint,则会出现此错误:
Error: Parse error on line 1:
{ Products: [{ Id: 1
--^
Expecting 'STRING', '}', got 'undefined'
您的字符串和键应加引号。 这是有效的JSON,将由JSON.parse()
正确解析
{
"Products": [
{
"Id": 1,
"Increment": 5,
"Max": 1000,
"Min": 25,
"allowed": false,
"Desc": "product description",
"Name": "Product Name",
"Qty": 0
}
]
}
您可以在此处阅读有关该标准的更多信息: https : //www.json.org/
当您在“字符串”变量中传递 JSON 内容时,也会发生这种情况,您需要使用单引号代替外部字符串的双引号
var data = "{ "nodes": [{ "id": 1, "text": "DefinitionFinder" },{ "id": 2, "text": "ProjectReference" },{ "id": 3, "text": "ReferenceManager" },{ "id": 4, "text": "ReferenceType" },{ "id": 5, "text": "EventStream" },{ "id": 6, "text": "AutoDisposable" },{ "id": 7, "text": "Handler" }], "links": [{ "from": 1, "to": 3 },{ "from": 2, "to": 4 },{ "from": 3, "to": 1 },{ "from": 3, "to": 2 }] }"
这是正确的方法
var data = '{ "nodes": [{ "id": 1, "text": "DefinitionFinder" },{ "id": 2, "text": "ProjectReference" },{ "id": 3, "text": "ReferenceManager" },{ "id": 4, "text": "ReferenceType" },{ "id": 5, "text": "EventStream" },{ "id": 6, "text": "AutoDisposable" },{ "id": 7, "text": "Handler" }], "links": [{ "from": 1, "to": 3 },{ "from": 2, "to": 4 },{ "from": 3, "to": 1 },{ "from": 3, "to": 2 }] }'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.