简体   繁体   中英

How to access nested array in json in javascript

I have a ajax call and as a return i have json object. 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:

[
    {
        "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. 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

If I output whole json reponse to console I get:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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