如何访问Class Dict类型中的数据?

问题描述 投票:0回答:1

我正在尝试使用json格式的特定天气数据,并使用Python3脚本访问数据的某些部分。实际数据尚未在线提供,因此我使用的是json格式的样本。这是json文件的内容:

    "observations": [{
        "stationID": "KNCCARY89",
        "obsTimeUtc": "2019-02-04T14:53:14Z",
        "obsTimeLocal": "2019-02-04 09:53:14",
        "neighborhood": "Highcroft Village",
        "softwareType": "GoWunder 1337.9041ac1",
        "country": "US",
        "solarRadiation": 436.0,
        "lon": -78.8759613,
        "realtimeFrequency": null,
        "epoch": 1549291994,
        "lat": 35.80221176,
        "uv": 1.2,
        "winddir": 329,
        "humidity": 71,
        "qcStatus": 1,
        "imperial": {
            "temp": 53,
            "heatIndex": 53,
            "dewpt": 44,
            "windChill": 53,
            "windSpeed": 2,
            "windGust": null,
            "pressure": 30.09,
            "precipRate": 0.0,
            "precipTotal": 0.0,
            "elev": 413
        }
    }]
}

这是我用来从我的Raspberry上的文件访问这个示例json数据的简单python脚本:

import json
from pprint import pprint

with open('data.json') as f:
    weather = json.load(f)

pprint(weather)

数据打印得很好,但我一直在努力使用嵌入式数据!

当我查询类型“类型(天气)”时,答案是“

似乎有效的唯一查询是“pprint(weather ['observation']),它显示了”观察“下面的所有json数据,但我无法弄清楚如何降低这个!

我是否必须将数据转换为另一种“类型”?

json python-3.5
1个回答
1
投票

weather ['observation']似乎是一个包含上述JSON中单个元素的数组。在Python中,那个天气['观察']因此应该是一个列表,并且要访问它的第一个元素,你会写

weather['observations'][0]

从那以后,您应该能够访问子元素,例如

weather['observations'][0]['stationID']
© www.soinside.com 2019 - 2024. All rights reserved.