在Javascript中读取复杂的JSON

时间:2016-03-06 16:12:42

标签: javascript json

我有一个json喜欢:

var data = [
   {
      "country":"Andorra",
      "code":"AD",
      "state":[
         {
            "state_code":"AD1",
            "state_description":"aaAndorra1"
         },
         {
            "state_code":"AD2",
            "state_description":"aaAndorra2"
         }
      ]
   }
]

我想通过state属性循环并获取state_code值

我正是这样做的:

for (var key in data) {
        if (data.hasOwnProperty(key)) {
            if(data[key].state.state_code === "AD1"){
                console.log(data[key].state.state_description);
        }
    }

我未定义。

请帮忙吗?

由于

6 个答案:

答案 0 :(得分:1)

尝试从外部对象进行迭代并打印它,

data.forEach(function(country){ //For the countries
  country.state.forEach(state){ //For the states
    console.log(state.state_code,state.state_description);
  });
});

作为旁注,在迭代数组时不应使用for-in循环。因为它将遍历enumerable中对象的所有prototypes属性。我看到你使用.hasOwnProperty(),这有助于避免这种情况,但在我们的例子中,使用for-in循环是不必要的。

DEMO

答案 1 :(得分:1)

试试这段代码

{{1}}

答案 2 :(得分:0)

如果你想要一个包含每个state_code的数组:

        var text = this.RefrencePro;
        int charsFitted;
        int linesFilled;

        var cn6 = new Font("Courier New", 6);

        var stringFormat = new StringFormat { Alignment= StringAlignment.Near };

        var pageSize = printDocument1.DefaultPageSettings.PaperSize;

        // How much size do we need?
        var measuredSize = g.MeasureString(
            text, 
            cn6, 
            new SizeF(pageSize.Width - startX, pageSize.Height),
            stringFormat, 
            out charsFitted, 
            out linesFilled);

        // Draw the string based on how much space
        // there is needed in the rectangle
        graphics.DrawString(
            text, 
            cn6, 
            new SolidBrush(Color.Black), 
            new RectangleF(new PointF(startX, startY +Offset), measuredSize),
            stringFormat);

        // offset based on the earlier measurements
        Offset = Offset + (int) measuredSize.Height;

请参阅here

答案 3 :(得分:0)



data.forEach(function(obj){
  
 var states = obj.state;
 if(Array.isArray(states)){
   
   states.forEach(function(state){
     if(state.state_code === "AD1"){
      console.log(state.state_description);
     }
   });
 } else {
   if(states.state_code === "AD1"){
      console.log(states.state_description);
   }
 }
  
});




答案 4 :(得分:0)

for...in语句迭代对象的可枚举属性

用于迭代Arrays使用for循环或Array#forEach函数

for (var i = 0; i < data.length; i++) {
    for (var j = 0; j < data[i].state.length; j++) {
        if (data[i].state[j].state_code === "AD1") {
            console.log(data[i].state[j].state_description);
        }
    }
}

答案 5 :(得分:0)

您的声明数据变量是一个对象数组。每个对象包含一个状态数组。因此,如果你想深入迭代,循环应该是这样的(它运行正常,我已经测试过)。

    for (var i = 0; i <= data.length; i++) {
        for(var j = 0; j <= data[i].state.length; j++){
            alert("The code is ::" + data[i].state[j].state_code);
        }
    }