在python 3.x中从JSON格式的数据中提取值

5kgi1eie  于 2023-02-01  发布在  Python
关注(0)|答案(1)|浏览(152)

我有一些python编程的经验,但是在如何处理大数据方面相当有限。我试着寻找是否有人问过类似的问题,但是只找到了数据不像这个例子那样"嵌套"的例子。如果已经有人问过或者在其他地方有过记录,请告诉我那个方向。
我所做的:我已进入本地气象站的应用程式界面,并以"request.get"取得JSON格式的数据。我已设法把数据列印出来,但我不明白如何在字典内取得特定的数值。
我尝试做的是:我想检索当前小时的"air_temperature"值,并且只打印时间戳和air_temperature值。我还想做一些其他事情,但是如果我知道如何检索这些特定值,我应该自己解决其余的问题。
示例代码:

import requests
import json
import xml.etree.ElementTree as ET

url = 'https://api.met.no/weatherapi/locationforecast/2.0'

parameters = {
    "lat": 40.416695,
    "lon": 8.306090,
}

response = requests.get(url, headers=headers, params= parameters)

#This loop was an attempt of trying to sort out the relevant data, but all the values in the 'properties' key got bunched together and I cant figure out how to access specific data
for key, value in response.json().items():   
    print(key)
    print(type(key), "key \n \n")
    print(value)
    print(type(value), "value \n \n")

#pseudocode of what I want to do:
for i = 0 to length(response.json().properties.timeseries)
    if response.json().properties.timeseries[i].time = "2023-01-29T09:00:00Z"
       print("timestamp: ", response.json().properties.timeseries[i].time, "temperature: ", response.json().properties.timeseries[i].data.instant.details.air_temperature)

数据示例可在此网页上找到:https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=60.10&lon=9.58

cczfrluj

cczfrluj1#

我假设您希望从返回的数据中获得第一个air_temperatur和时间:

import requests

url = 'https://api.met.no/weatherapi/locationforecast/2.0/compact'
parameters = {
    "lat": 40.416695,
    "lon": 8.306090,
}

headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/109.0'}

data = requests.get(url, params=parameters, headers=headers).json()

current = data['properties']['timeseries'][0]
print(current['time'], current['data']['instant']['details']['air_temperature'])

图纸:

2023-01-29T10:00:00Z 10.8

相关问题