1

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!

3
  • 1
    Looks like your vouchers field is actually a string. Try to check its type console.info(typeof json.vouchers). If it is so, parse it manually by following json.vouchers = JSON.parse(json.vouchers) Commented May 27, 2015 at 22:13
  • 1
    BTW, there is no such thing as JSON object. You either have a JSON string, or you have converted it to an object. Commented May 27, 2015 at 22:15
  • thanks for tips. I just copied what I had in console. And it is 'String'. Checked with typeof Commented May 27, 2015 at 22:25

1 Answer 1

2

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

var v = JSON.parse(json.vouchers)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.