使用 JQuery 加载 JSON 后,我得到一个而不是多个条目
我构建了一些
{
"News": {
"Article": {"title": "test"},
"Article": { "title": "test" },
/*Snipped*/
"Article": { "title": "test" },
"Article": { "title": "test" }
},
"count": "20"
}
在 JSON 格式化程序 中验证的 JSON。但是当我尝试通过 jQuery 获取这些数据时,我没有得到预期的结果:
$.getJSON('php/json.php', function(data) {
console.log(data);
});
结果:
News: Object
Article: Object
title: "test"
__proto__: Object
__proto__: Object
count: "20"
但是我的其他 19 个 Article 对象在哪里?我是 JSON 和 jQuery 的 getJSON
新手。我有什么遗漏的吗?
I've built some JSON
{
"News": {
"Article": {"title": "test"},
"Article": { "title": "test" },
/*Snipped*/
"Article": { "title": "test" },
"Article": { "title": "test" }
},
"count": "20"
}
which validates in a JSON formatter. But when I try to ingest this data through jQuery I don't get what's expected:
$.getJSON('php/json.php', function(data) {
console.log(data);
});
Results:
News: Object
Article: Object
title: "test"
__proto__: Object
__proto__: Object
count: "20"
But where are my 19 other Article objects? I'm new to JSON and jQuery's getJSON
. Is there anything I'm missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
JavaScript 对象是字典,这意味着名称必须是唯一的。您正在复制
Article
,因此每个实例都会覆盖前一个实例(或被忽略;我不知道解析器采用哪个路径)。要解决此问题,您需要将此名称定义为引用数组:
但是您可以进一步减少此名称,假设所有新闻项都是文章,因为
count
变得多余:JavaScript objects are dictionaries, which means that the name must be unique. You're replicating
Article
, so each instance overwrites the previous (or is ignored; I don't know which path the parser takes).To fix, you need to define this name as referencing an array:
But you could probably reduce this further, assuming that all news items are articles, because
count
becomes superfluous:更好的格式是
So you can do with every。
A better format would be
So you can do with each.
您多次定义了
Article
键。这不是语法错误(这就是格式化程序不抱怨的原因),而是逻辑错误。您应该使用数组代替。You defined the
Article
-key multiple times. This is not a syntax error (which is why the formatter does not complain) but rather a logical one. You should use an array instead.