简体   繁体   English

如何在JavaScript中访问json中的嵌套数组

[英]How to access nested array in json in javascript

I have a ajax call and as a return i have json object. 我有一个ajax调用,作为回报,我有json对象。 I can access information like 'status' or 'info' with 我可以通过访问“状态”或“信息”之类的信息

// handle a successful response
                        success : function(json) {
                            if (json.result == 'ok') {
                                console.log('sanity check - iccid:' + json.iccid);
                                console.log('sanity check - amount:' + json.amount);
                            } else if (json.result == 'error'){
                                console.log('sanity check - error: ' + json.info);
                            };

but in this json object i have another array: 但是在这个json对象中我有另一个数组:

[
    {
        "pk": 31,
        "model": "simcard.voucher",
        "fields": {
            "amount": 5,
            "voucher_no": "4762"
        }
    },
    {
        "pk": 32,
        "model": "simcard.voucher",
        "fields": {
            "amount": 5,
            "voucher_no": "4912"
        }
    }
]

First I would like to get vouchers quantity. 首先,我想获得代金券数量。 I tried with json.vouchers.length but I got characters quantity. 我尝试了json.vouchers.length但我得到了字符数量。 Then I would like to iterate over vouchers. 然后,我想遍历凭证。 With: 附:

var v = json.vouchers;
 for(var i in v)
  {
   console.info( v[i].pk);
   console.info( v[i].model);
   console.info( v[i].fields.amount);
   console.info( v[i].fields.voucher_no);
   }

I got error TypeError: v[i].fields is undefined 我收到错误TypeError: v[i].fields is undefined

If I output whole json reponse to console I get: 如果我将整个json响应输出到控制台,则会得到:

Object { amount=10,  iccid="894422",  vouchers="[{"pk": 31, "model": "simcard.voucher", "fields": {"amount": 5, "voucher_no": "4762"}}, {"pk": 32, "model": "simcard.voucher", "fields": {"amount": 5, "voucher_no": "4912"}}]"  }

Hope you can guide me. 希望你能指导我。 Thanks in advance! 提前致谢!

我认为您必须将json解析为js对象。

var v = JSON.parse(json.vouchers)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM