http://chriscargile.com/dictionary/tojson/moon.js
例如,我想在这里检索单词“moon”的所有定义。 我尝试过使用 jQuery
$.getJSON(url, function (json) {
alert(json.definition)
})
这只会返回最后一个定义。
最佳答案
问题是因为重复键在 JSON 中无效。您需要在作为数组一部分的对象中创建每个 pos
和 definition
属性。如果您将 JSON 文件粘贴到此 validator你会明白为什么你只能返回一个条目。
正确的格式应该是这样的:
{
"lemma": "moon",
"definitions": [
{
"pos": "n",
"definition": "the natural satellite of the Earth",
"samples": [
"the average distance to the Moon is 384,400 kilometers",
"men first stepped on the moon in 1969"
]
},
{
"pos": "n",
"definition": "any object resembling a moon",
"samples": [
"he made a moon lamp that he used as a night light",
"the clock had a moon that showed various phases"
]
}
]
}
然后您可以使用 $.each
(如果您想使用原生的,甚至可以使用普通的 for
循环)迭代每个定义及其示例。
关于javascript - 从具有重复键的 JSON 文件中检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19846551/