gerpaick
gerpaick

Reputation: 799

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!

Upvotes: 1

Views: 67

Answers (1)

Eduardo Pérez
Eduardo Pérez

Reputation: 488

I think you have to parse your json to a js object.

var v = JSON.parse(json.vouchers)

Upvotes: 2

Related Questions