[英]Is there a way to print out certain elements of the JSON file in python?
I am using a (dutch) weather API and the result is showing a lot of information.我正在使用(荷兰)天气 API,结果显示了很多信息。 However, I only want to print the temperature and location.
但是,我只想打印温度和位置。 Is there a way to filter out these keys?
有没有办法过滤掉这些键?
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())
result:结果:
{
"liveweer": [
{
"place": "Utrecht",
"temp": "7.7",
"gtemp": "5.2",
"summa": "Dry after rain",
"lv": "89",
etc.
How do I only print out the place and temp?我如何只打印出地点和温度? Thanks in advance
提前致谢
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']}")
output输出
Temp in Utrecht is 8.0
Note that you can use convenient Response.json()
method请注意,您可以使用方便的
Response.json()
方法
Try this:尝试这个:
x=response.json()
print(x['liveweer'][0]['place'])
print(x['liveweer'][0]['temp'])
If you expect the API to returns you a list of place, you can do:如果您希望 API 返回一个地点列表,您可以执行以下操作:
>>> {'liveweer': [{'plaats': item['plaats'], 'temp': item['temp']}] for item in response.json()['liveweer']}
{'liveweer': [{'plaats': 'Utrecht', 'temp': '8.0'}]}
If you are only interested in working with place and temp I would advise making a new dictionary.如果您只对使用 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.