[英]JSON not well formed error
在下面的代码中,
<head>
<meta charset="UTF-8">
<title>JSON ex</title>
<script type = "text/javascript"
src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language = "javascript">
var accountGrid = [];
$(document).ready(function(){
$.getJSON('result.json', function(entry){
accountGrid.push({
name: entry.name,
marketValue: entry.marketValue,
cash: entry.cash,
legend: entry.legend
});
});
});
</script>
</head>
<body>
</body>
result.json
{
'name': 'Account1',
'marketValue': '10990',
'cash': '199926',
'legend': 'orange'
},
{
'name': 'Account2',
'marketValue': '156590',
'cash': '133856',
'legend': 'darkorange'
}
我看到JSON not well formed
错误。 result.json
位于同一文件夹中。
由于此错误, accountGrid
空。
在执行jQuery.getJSON
说not well formed
错误的错误是什么意思?
JSON必须是单个值(对象,数组等)
JSON对象应为单个值。 您所拥有的是两个用逗号分隔的对象。 也许您可以将每个对象分配为单个对象的成员。
# a JSON object consists of a single value definition
value
string
number
object
array
true
false
null
# this value can be an object
object
{}
{ members }
# or an array
array
[]
[ elements ]
______
单引号是非法的
JSON禁止对字符串使用单引号( '
)。
# a string consists of chars wrapped in double-quotation marks
string
""
" chars "
因此,将所有单引号替换为双引号。
考虑以上两件事,您将得到如下结果:
{
"key1": {
"name": "Brokerage Account 3",
"marketValue": "1999990",
"cash": "1995826",
"legend": "orange"
},
"key2": {
"name": "Account 3",
"marketValue": "1949990",
"cash": "1695856",
"legend": "darkorange"
}
}
[ 在线试用 ]
______
将对象放在数组中
或者,按照@Gerald Schneider的建议,将对象放置在数组中。 规范说value
(上面定义)可以是一个array
:
array
[]
[ elements ] # elements can multiple values, e.g. objects
因此,您的JSON如下所示:
[
{
"name": "Account1",
"marketValue": "10990",
"cash": "199926",
"legend": "orange"
},
{
"name": "Account2",
"marketValue": "156590",
"cash": "133856",
"legend": "darkorange"
}
]
[ 在线试用 ]
______
消耗解析后的JSON (其中JSON是数组)
如果将数据表示为数组,则回调应仅将生成的已解析JSON分配给accountGrid
变量:
<script type="text/javascript" language = "javascript">
var accountGrid = [];
$(document).ready(function(){
$.getJSON('result.json', function(entry){
accountGrid = entry;
});
});
</script>
另外,如果您想将entry的值附加到accountGrid
:
accountGrid = accountGrid.concat(entry);
______
将来编写JSON
我建议您在支持JSON语法高亮显示的IDE中编辑JSON文件,然后在编辑器中引发这些问题。 或者, 使用许多可用的在线工具之一 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.