gpt4 book ai didi

javascript - 在 JSON 文件中搜索。

转载 作者:行者123 更新时间:2023-12-03 11:17:53 25 4
gpt4 key购买 nike

我正在尝试使用 ISO (cca2) 代码搜索一个国家/地区的首都。

我正在执行以下操作:

 var json =   $.getJSON('Countries.json', function(data)
{
return data;
});

var CapitalCity = getCapitalByCCA2(json, code.toString().toUpperCase());

alert(CapitalyCity);

function getCapitalByCCA2(json, code) {
for (var i = 0; i < json.length; i++) {
if (json[i].cca2 === code.toString().toUpperCase()) {
return json[i].capital;
console.log(json[i]);
}
}
return null;
};

JSON文件的结构:

[
{
"name": {
"common": "Afghanistan",
"official": "Islamic Republic of Afghanistan",
"native": {
"common": "\u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627\u0646",
"official": "\u062f \u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627\u0646 \u0627\u0633\u0644\u0627\u0645\u064a \u062c\u0645\u0647\u0648\u0631\u06cc\u062a"
}
},
"tld": [".af"],
"cca2": "AF",
"ccn3": "004",
"cca3": "AFG",
"currency": ["AFN"],
"callingCode": ["93"],
"capital": "Kabul",
"altSpellings": ["AF", "Af\u0121\u0101nist\u0101n"],
"relevance": "0",
"region": "Asia",
"subregion": "Southern Asia",
"nativeLanguage": "pus",
"languages": {
"prs": "Dari",
"pus": "Pashto",
"tuk": "Turkmen"
},
"translations": {
"cym": "Affganistan",
"deu": "Afghanistan",
"fra": "Afghanistan",
"hrv": "Afganistan",
"ita": "Afghanistan",
"jpn": "\u30a2\u30d5\u30ac\u30cb\u30b9\u30bf\u30f3",
"nld": "Afghanistan",
"rus": "\u0410\u0444\u0433\u0430\u043d\u0438\u0441\u0442\u0430\u043d",
"spa": "Afganist\u00e1n"
},
"latlng": [33, 65],
"demonym": "Afghan",
"borders": ["IRN", "PAK", "TKM", "UZB", "TJK", "CHN"],
"area": 652230
},
{
"name": {
"common": "\u00c5land Islands",
"official": "\u00c5land Islands",
"native": {
"common": "\u00c5land",
"official": "Landskapet \u00c5land"
}
},
"tld": [".ax"],
"cca2": "AX",
"ccn3": "248",
"cca3": "ALA",
"currency": ["EUR"],
"callingCode": ["358"],
"capital": "Mariehamn",
"altSpellings": ["AX", "Aaland", "Aland", "Ahvenanmaa"],
"relevance": "0",
"region": "Europe",
"subregion": "Northern Europe",
"nativeLanguage": "swe",
"languages": {
"swe": "Swedish"
},
"translations": {
"deu": "\u00c5land",
"fra": "\u00c5land",
"hrv": "\u00c5landski otoci",
"ita": "Isole Aland",
"jpn": "\u30aa\u30fc\u30e9\u30f3\u30c9\u8af8\u5cf6",
"nld": "\u00c5landeilanden",
"rus": "\u0410\u043b\u0430\u043d\u0434\u0441\u043a\u0438\u0435 \u043e\u0441\u0442\u0440\u043e\u0432\u0430",
"spa": "Alandia"
},
"latlng": [60.116667, 19.9],
"demonym": "\u00c5landish",
"borders": [],
"area": 1580
}

}

]

问题是未获取数据。

我做错了什么?

最佳答案

您应该使用 grep 来过滤 json,如下所示:

var returnedData = $.grep(json, function (element, index) {
return element.cca2 === code.toString().toUpperCase();
});

returnData 将包含过滤后的 json 数组。

我在您的代码中没有看到 var code 的任何定义。

关于javascript - 在 JSON 文件中搜索。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27254406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com