运行以下代码时,为什么会收到此错误消息。
参数列表之后的Uncaught SyntaxError:missing)
<html>
<head>
<title>read json</title>
<script type="text/javascript">
var load = function() {
var data='{"took": 2,"timed_out": false,"_pieces": { "total": 5, "successful": 5, "failed": 0},"hits": { "total": 117, "max_score": 0, "hits": []},"aggregations": { "2": { "doc_error": 228, "sum_other_t": 10705, "buckets": [ { "key": "2016", "count": 196 }, { "key": "2015", "count": 163 }, { "key": "2014", "count": 159 }, { "key": "2013", "count": 157 }, { "key": "2012", "count": 157 } ] }}}';
var myData = JSON.parse(data);
console.log(myData.aggregations.2.buckets.length) ;
//console.log(myData) ;
}
</script>
</head>
<body>
hi
</body>
</html>
答案 0 :(得分:4)
根据文档 dot notation 只能在
时使用在此代码中,属性必须是有效的JavaScript标识符,即一系列字母数字字符,也包括下划线(“_”)和美元符号(“$”),它们不能以数字开头。例如,object。$ 1有效,而object.1不是。
因此,您需要使用bracket notation([]
)访问媒体资源2
<html>
<head>
<title>read json</title>
<script type="text/javascript">
var load = function() {
var data = '{"took": 2,"timed_out": false,"_pieces": { "total": 5, "successful": 5, "failed": 0},"hits": { "total": 11537, "max_score": 0, "hits": []},"aggregations": { "2": { "_upper_bound": 228, "doc_count": 10705, "buckets": [ { "key": "2016", "count": 196 }, { "key": "2015", "count": 163 }, { "key": "2014", "count": 159 }, { "key": "2013", "count": 157 }, { "key": "2012", "count": 157 } ] }}}';
var myData = JSON.parse(data);
console.log(myData.aggregations[2].buckets.length);
//console.log(myData) ;
}
</script>
</head>
<body onload="load()">
hi
</body>
</html>
仅供参考:此外,无需将其定义为JSON字符串,它也是JavaScript中的有效对象格式,您可以将其定义为对象。
<html>
<head>
<title>read json</title>
<script type="text/javascript">
var load = function() {
var data = {"took": 2,"timed_out": false,"_pieces": { "total": 5, "successful": 5, "failed": 0},"hits": { "total": 11537, "max_score": 0, "hits": []},"aggregations": { "2": { "doc_count_error_upper_bound": 228, "sum_other_doc_count": 10705, "buckets": [ { "key": "2016", "count": 196 }, { "key": "2015", "count": 163 }, { "key": "2014", "count": 159 }, { "key": "2013", "count": 157 }, { "key": "2012", "count": 157 } ] }}};
console.log(data.aggregations[2].buckets.length);
//console.log(myData) ;
}
</script>
</head>
<body onload="load()">
hi
</body>
</html>