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

时间:2019-02-13 21:23:56

标签: json python-3.5

我正在尝试使用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 ['observations'])”,它显示了“ observations”下的所有json数据,但我不知道如何降低此值!

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

1 个答案:

答案 0 :(得分:1)

weather ['observations']似乎是上面的JSON中只有一个元素的数组。因此,在Python中,weather ['observations']应该是一个列表,要访问其第一个元素,您可以编写

weather['observations'][0]

由此,您应该能够访问子元素,例如

weather['observations'][0]['stationID']