簡體   English   中英

有沒有辦法在python中打印出JSON文件的某些元素?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM