简体   繁体   English

如何从嵌套数组中获取值? JSON

[英]How to get a value from nested arrays? JSON

I have a problem with parsing tickets. 我在解析票证时遇到问题。 There is a JSON link that contains the following data: json file 有一个JSON链接,其中包含以下数据: json文件

{"success":true,"data":{"AAE":{"2":{"price":48973,"airline":"AF","flight_number":1745,"departure_at":"2018-09-04T18:45:00Z","return_at":"2018-09-14T07:15:00Z","expires_at":"2018-09-02T06:57:21Z"},"3":{"price":67240,"airline":"TP","flight_number":1235,"departure_at":"2018-09-04T07:15:00Z","return_at":"2018-09-14T07:15:00Z","expires_at":"2018-09-02T06:57:21Z"}},"AAH":{"1":{"price":34049,"airline":"LH","flight_number":1453,"departure_at":"2018-09-30T09:05:00Z","return_at":"2018-10-02T07:40:00Z","expires_at":"2018-09-03T11:37:06Z"},"2":{"price":35838,"airline":"LH","flight_number":1453,"departure_at":"2018-09-30T09:05:00Z","return_at":"2018-10-02T11:39:00Z","expires_at":"2018-09-03T11:37:06Z"}},"AAL":{"1":{"price":23258,"airline":"KL","flight_number":904,"departure_at":"2018-12-08T18:00:00Z","return_at":"2018-12-15T06:00:00Z","expires_at":"2018-09-03T13:27:58Z"},"2":{"price":21867,"airline":"AF","flight_number":1745,"departure_at":"2018-12-08T20:00:00Z","return_at":"2018-12-15T18:15:00Z","expires_at":"2018-09-03T13:27:58Z"},"3":{"price":30639,"airline":"AF","flight_number":1145,"departure_at":"2018-12-08T09:45:00Z","return_at":"2018-12-15T06:00:00Z","expires_at":"2018-09-03T13:27:58Z"}},"AAQ":{"0":{"price":5354,"airline":"FV","flight_number":5515,"departure_at":"2018-09-16T04:20:00Z","return_at":"2018-10-04T12:40:00Z","expires_at":"2018-08-31T20:53:40Z"},"1":{"price":8590,"airline":"FV","flight_number":5515,"departure_at":"2018-09-16T04:20:00Z","return_at":"2018-10-04T15:05:00Z","expires_at":"2018-08-31T20:53:40Z"},"2":{"price":13702,"airline":"U6","flight_number":79,"departure_at":"2018-10-04T11:20:00Z","return_at":"2018-10-10T12:40:00Z","expires_at":"2018-09-03T06:47:01Z"}},"AAR":{"1":{"price":24418,"airline":"OK","flight_number":905,"departure_at":"2018-09-19T22:10:00Z","return_at":"2018-09-25T09:35:00Z","expires_at":"2018-09-02T21:16:33Z"},"2":{"price":20805,"airline":"AY","flight_number":712,"departure_at":"2018-09-19T11:50:00Z","return_at":"2018-09-25T16:55:00Z","expires_at":"2018-09-02T21:16:33Z"},"3":{"price":36316,"airline":"BT","flight_number":425,"departure_at":"2018-09-19T09:45:00Z","return_at":"2018-09-25T09:35:00Z","expires_at":"2018-09-02T21:16:33Z"}},

My code: 我的代码:

import json
from urllib.request import Request, urlopen

request = Request("http://api.link")
response_body = urlopen(request).read()

tickets = json.loads(response_body)

for item in tickets['data']:
    price = item['AAL']['1']['price']
    print(price)

I tried various options to get the value of price, but nothing happened. 我尝试了各种选择来获得价格价值,但是什么也没发生。

Help me get this value 帮我获得这个价值

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 json

tickets = 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.

I think that these "1" and "2" are items of list not dict . 我认为这些“ 1”和“ 2”是list项而不是dict And you need to iterate through them. 您需要遍历它们。 Try to handle like here: 尝试像这样处理:

import json
from urllib.request import Request, urlopen

request = 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)

It is casting item as a string in the for loop. 它在for循环中将项目强制转换为字符串。 So when you're calling ['1'] it is throwing an error, where as if you set it to an integer, ie [1] it would bring back the second char of the key, in this case 'A' from 'AAL'. 因此,当您调用['1']时会引发错误,就好像您将其设置为整数一样,即[1]它将带回键的第二个字符,在这种情况下是'' AAL”。 This will work if you mod it to fit your needs. 如果您对其进行了修改以适合您的需求,那么它将起作用。

import json
from urllib.request import Request, urlopen

request = 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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