[英]Is there a way to print out certain elements of the JSON file in python?
我正在使用(荷兰)天气 API,结果显示了很多信息。 但是,我只想打印温度和位置。 有没有办法过滤掉这些键?
from pip._vendor import requests
import json
response = requests.get(" http://weerlive.nl/api/json-data-10min.php?key=demo&locatie=52.0910879,5.1124231")
def jprint(obj):
weer = json.dumps(obj, indent=2)
print(weer)
jprint(response.json())
结果:
{
"liveweer": [
{
"place": "Utrecht",
"temp": "7.7",
"gtemp": "5.2",
"summa": "Dry after rain",
"lv": "89",
etc.
我如何只打印出地点和温度? 提前致谢
import requests
response = requests.get(" http://weerlive.nl/api/json-data-10min.php?key=demo&locatie=52.0910879,5.1124231")
data = response.json()
for station in data["liveweer"]:
print(f"Temp in {station['plaats']} is {station['temp']}")
输出
Temp in Utrecht is 8.0
请注意,您可以使用方便的Response.json()
方法
尝试这个:
x=response.json()
print(x['liveweer'][0]['place'])
print(x['liveweer'][0]['temp'])
如果您希望 API 返回一个地点列表,您可以执行以下操作:
>>> {'liveweer': [{'plaats': item['plaats'], 'temp': item['temp']}] for item in response.json()['liveweer']}
{'liveweer': [{'plaats': 'Utrecht', 'temp': '8.0'}]}
如果您只对使用 place 和 temp 感兴趣,我建议您制作一本新词典。
import requests
r = requests.get(" http://weerlive.nl/api/json-data-10min.php?key=demo&locatie=52.0910879,5.1124231")
if r.status_code == 200:
data = {
"place" : r.json()['liveweer'][0]["place"],
"temp": r.json()['liveweer'][0]["temp"],
}
print(data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.