在下面的代码中,
<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
变空。
执行not well formed
后,jQuery.getJSON
错误是什么意思?
答案 0 :(得分:6)
让我们考虑一下JSON spec ......
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>
或者,如果您想将条目值附加到accountGrid
:
accountGrid = accountGrid.concat(entry);
______
将来编写JSON
我建议你在支持JSON语法高亮的IDE中编辑JSON文件,然后在编辑器中引发这些问题。或者,Try it out online。