There is a json string:

{ "success":true, "data":{ "BKK":{ "origin":"IEV", "destination":"BKK", "price":7936, "transfers":1, "airline":"FZ", "flight_number":730, "departure_at":"2017-01-16T03:20:00Z", "return_at":"2017-03-08T12:10:00Z", "expires_at":"2016-12-29T12:07:13Z" }, "DXB":{ "origin":"IEV", "destination":"DXB", "price":2378, "transfers":0, "airline":"FZ", "flight_number":728, "departure_at":"2017-01-12T14:25:00Z", "return_at":"2017-01-31T19:55:00Z", "expires_at":"2016-12-29T18:48:32Z" } }, "error":null, "currency":"UAH" } 

And when I try to get access to the field value, for example, origin, I get the error Uncaught TypeError: Cannot read property 'origin' of undefined :

 for(var i = 0; i < 3; i++) { pwf.append('<div class="text">Пункт отправки:' + json.data[i].origin + '</div>'); } 

I suspect that this is due to the fact that the data arrays have different keys, but I don’t know how to solve the problem.

    1 answer 1

    json.data not an array, but an ordinary object. You can go through all its properties:

     for (var p in json.data) { pwf.append('<div class="text">Пункт отправки:' + json.data[p].origin + '</div>'); } 
    • Is it possible to somehow convert a JS object into a json array? - JamesJGoodwin
    • It is possible, but it will be much more difficult. I understand that JSON comes from some kind of external service that you do not affect? Or is it possible to correct what comes up? By the way, in the JSON-code above there is not enough 1 closing bracket. - Zergatul
    • Yes. I get a json string from the API and, in principle, it’s more convenient for me to work with json directly than with objects. - JamesJGoodwin