【问题标题】:Is there a way to print out certain elements of the JSON file in python?有没有办法在 python 中打印出 JSON 文件的某些元素?
【发布时间】:2021-02-16 12:46:58
【问题描述】:

我正在使用(荷兰语)天气 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.

如何只打印地点和温度? 提前致谢

【问题讨论】:

    标签: python json api key


    【解决方案1】:

    试试这个:

    x=response.json()
    
    print(x['liveweer'][0]['place'])
    print(x['liveweer'][0]['temp'])
    

    【讨论】:

    • 是的,它运行良好。你能解释一下'[0]'吗?
    • [0] 指的是 x['liveweer'] 列表(它是一个字典)的第一个元素。请记住,我的代码适用于您提供的这种特定结构。如果结构发生变化,它就无法工作。但是您可以在相同的逻辑上调整代码
    【解决方案2】:

    如果您希望 API 向您返回地点列表,您可以这样做:

    >>> {'liveweer': [{'plaats': item['plaats'], 'temp': item['temp']}] for item in response.json()['liveweer']}
    {'liveweer': [{'plaats': 'Utrecht', 'temp': '8.0'}]}
    

    【讨论】:

    • 不完全是我想要的。但这也很有效,将来会很有用。
    【解决方案3】:
    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()方法

    【讨论】:

      【解决方案4】:

      如果您只对使用地点和温度感兴趣,我建议您制作一本新字典。

      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)
          
      

      【讨论】:

        猜你喜欢
        • 2020-09-05
        • 1970-01-01
        • 2020-03-25
        • 1970-01-01
        • 1970-01-01
        • 2020-03-11
        • 1970-01-01
        • 2018-05-16
        • 2017-02-17
        相关资源
        最近更新 更多