How to get a value from nested arrays? JSON How to get a value from nested arrays? JSON json json

How to get a value from nested arrays? JSON


I didn't try this with the raw data you (finally) added in your question—although still not as text as I suggested. Instead I manually typed in (and fixed the formatting of) the snippet that was shown in the image you originally posted.

Regardless, the following should at least be close and shows you how to access the various parts of the data structure:

response_body = '''{    "success": true,    "data": {        "AAL": {            "1": {                "price": 53411,                "airline": "KL",                "flight_number": 904,                "departure_at": "2018-08-31T17:00:002",                "return_at": "2018-09-01T18:20:002",                "expires_at": "2018-08-31T17:00:OOZ"            },            "2": {                "price": 56035,                "airline": "BT",                "flight_number": 429,                "departure_at": "2018-08-31T15:25:002",                "return_at": "2018-09-01To6:35:002",                "expires_at": "2018-08-31T15:25:OOZ"            }        },        "AAQ": {            "0": {                "price": 6242,                "airline": "DP",                "flight_number": 147,                "departure_at": "2018-09-15T21:00:002",                "return_at": "2018-10-05T12:40:002",                "expires_at": "2018-09-03T13:18:222"            }        }    }}'''

Code to process the data:

import jsontickets = json.loads(response_body)for airport, flights in tickets['data'].items():    print('airport:', airport)    for id, flight in flights.items():        print('  id:', id)        print('    airline:', flight['airline'])        print('    flight_number:', flight['flight_number'])        print('    price:', flight['price'])  # Here's how to get the price.


It is casting item as a string in the for loop. So when you're calling ['1'] it is throwing an error, where as if you set it to an integer, i.e. [1] it would bring back the second char of the key, in this case 'A' from 'AAL'. This will work if you mod it to fit your needs.

import jsonfrom urllib.request import Request, urlopenrequest = Request("http://api.travelpayouts.com/v1/prices/cheap?origin=MOW&page=1&      token=77e84779fa444c14806f022f6c41b7fe")response_body = urlopen(request).read()tickets = json.loads(response_body)for item in tickets['data']:    if item == 'AAL':        price = tickets['data'][item]['1']['price']print(price)


I think that these "1" and "2" are items of list not dict. And you need to iterate through them. Try to handle like here:

import jsonfrom urllib.request import Request, urlopenrequest = Request("http://api.link")response_body = urlopen(request).read()tickets = json.loads(response_body)for key, items in tickets['data'].items():    for item in items:        price = item['price']        print(price)