【问题标题】:How do I navigatin nested json data如何在嵌套的 json 数据中导航
【发布时间】:2012-04-11 20:38:59
【问题描述】:

在导航 json 文件方面我需要一点帮助。

我希望从这样的返回中获取所有国家/地区名称:

[{"country":
    {
     "225":["United Kingdom","Europe"],
     "206":["Switzerland","Europe"],
     "176":["Romania","Europe"],
     "127":["Madagascar","AMEA"],
     "217":["Tunisia","AMEA"]
    }
  }]

如果我不知道或没有 225、206...等的列表,我该如何解决?

【问题讨论】:

标签: jquery json


【解决方案1】:
var arr = [
    {
       "country": {
            "225":["United Kingdom","Europe"],
            "206":["Switzerland","Europe"],
            "176":["Romania","Europe"],
            "127":["Madagascar","AMEA"],
            "217":["Tunisia","AMEA"]
       }
    }
]

如果你有一个键(例如225),那么arr[0]["country"]["225"]会返回一个带有["United Kingdom","Europe"]的数组

如果您想获取键列表(和相应的值),只需使用

var countryObj = arr[0]["country"];
for (key in countryObj) {
   if (countryObj.hasOwnProperty(key)) {
      console.log(key);                /* e.g. 206 */ 
      console.log(countryObj[key]);    /* e.g. ["Switzerland","Europe"] */
      console.log(countryObj[key][0]); /* e.g. "Switzerland" */
  }
}

【讨论】:

  • 感谢 Calderan - 当我查看其他导航数组示例时,这没有任何意义。干杯:)
【解决方案2】:

您也可以将其用作数组,

如果您不知道键 255,256 并且只想获取国家/地区,那么可能一个好方法是使用 jquery 来遍历 jquery 对象

$(arr[0]["country"]).each(function(key,country){
  alert(country);
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 2021-11-05
    • 2020-09-08
    • 1970-01-01
    相关资源
    最近更新 更多