gpt4 book ai didi

javascript - 如何使用 javascript 并根据提供的输入获取 JSON 数据?

转载 作者:行者123 更新时间:2023-12-02 19:36:32 25 4
gpt4 key购买 nike

如何使用 JavaScript 并根据提供的输入获取 JSON 数据?

我的 JSON 文件如下所示...

{
"Name1": {
"id": "32313",
"latitude": "57.1",
"longitude": "9.85",
"timezone": "2",
"city": "Aalborg",
"country": "Denmark",
"country_code": "DK"
},
"Name2": {
"id": "32314",
"latitude": "56.15",
"longitude": "10.2167",
"timezone": "2",
"city": "Aarhus",
"country": "Denmark",
"country_code": "DK"
},
"Name3": {
"id": "122109",
"airport_name": "Aasiaat",
"latitude": "68.7",
"longitude": "-52.75",
"timezone": "-3",
"city": "Aasiaat",
"country": "Greenland",
"country_code": "GL"
},
"Name4": {
"id": "116713",
"latitude": "30.371111",
"longitude": "48.228333",
"timezone": "4",
"city": "Abadan",
"country": "Iran",
"country_code": "IR"
},
"Name5": {
"id": "116711",
"latitude": "53.74",
"longitude": "91.385",
"timezone": "7",
"city": "Abakan",
"country": "Russia",
"country_code": "RU"
},
"Name6": {
"id": "120587",
"latitude": "49.05",
"longitude": "-122.2833",
"timezone": "-7",
"city": "Abbotsford",
"country": "Canada",
"country_code": "CA"
},
"Name7": {
"id": "116759",
"latitude": "13.847",
"longitude": "20.844333",
"timezone": "1",
"city": "Abeche",
"country": "Chad",
"country_code": "TD"
},
"Name8": {
"id": "32325",
"latitude": "57.2",
"longitude": "-2.2",
"timezone": "1",
"city": "Aberdeen",
"country": "United Kingdom",
"country_code": "GB"
}
}

从上面的 JSON 文件...我需要获取以下内容:

  1. 获取国家/地区列表
  2. 根据提供的国家/地区名称获取城市名称。

请帮我解析上面的 JSON 文件....

谢谢,尤干达尔

最佳答案

var countries = [];
// Vanilla Javascript
// Get Array of countries
for( var name in json ){
countries.push(json[name]["country"]);
}
// Get city name based on country name

var getCities = function(country){
var cities = [];
for( var name in json ){
if (country === json[name]["country"]){
cities.push(name);
}
}
return cities;
}

// Usage
var cities = getCities("Denmark"); //

关于javascript - 如何使用 javascript 并根据提供的输入获取 JSON 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10876854/

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