【问题标题】:How do I filter a json print to only spit out certain values如何过滤 json 打印以仅吐出某些值
【发布时间】:2021-07-19 01:06:27
【问题描述】:

代码:

response = requests.request("GET", url, headers=headers, params=querystring)
print(json.dumps(response.json(), indent=4))

输出:

{
    "errors": [],
    "result": [
        {
            "hex": "18:93:d7",
            "b16": "1893d7",
            "name": "texas instruments",
            "address": "12500 ti blvd dallas tx 75243 us"
        }
    ]
}

我的目标:

我只想打印十六进制、姓名和地址。我也想美化它,但在我这样做之前我需要过滤输出

【问题讨论】:

  • response.json() 只是一个迭代的 list-dict 对象;您可以简单地删除response.json()的“result”条目的“b16”条目,它是字典中的字典条目。
  • data = response.json()print( data["result"][0]["hex"] )

标签: python json python-requests


【解决方案1】:
for i in 'hex', 'name', 'address':
    print(i.capitalize(), response.json()['result'][0][i])

你会得到:

Hex 18:93:d7
Name texas instruments
Address 12500 ti blvd dallas tx 75243 us

【讨论】:

  • 它告诉我结果未确定,我不知道为什么,我马上回来
  • 使用你提供的json,它在我的电脑上运行良好。检查返回值是否与您发布的相同。
  • 别介意我是愚蠢的,我忘记了我的 api 密钥哈哈。一切正常,非常感谢朋友
  • 这是我的荣幸。 ?
  • 老实说,我正在学习,我注意到您添加了 i.capitalize 以将结果大写。是否可以做同样的事情来添加“:”的后缀
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-01
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
  • 2020-08-22
  • 2014-04-27
  • 2011-03-26
相关资源
最近更新 更多