【问题标题】:Loop through json and return only true elements循环 json 并仅返回 true 元素
【发布时间】:2019-06-20 04:35:53
【问题描述】:

通过 API,我接收 json 输出,而不是将所有输出写入分析,我只想要具有“真”值的数据。

原始 json 数据示例:

scans:
   Scanner1:
      detected: false
      version: "1.1.1.1"
      result: null
      update: "14123412"
   Scanner2:
      detected: true
      version: "2.2.2.2"
      result: "trojan"
      update: "23142551"

Python 代码

with open('C:\\output.json', 'w') as outfile:
   for item in data["scans"]:
      if 'item["detected"] === true
         json.dump(data)

期望的输出

scans:
    Scanner2:
       detected: true
       version: "2.2.2.2"
       result: "trojan"
       update: "23142551"

这绝对行不通,我不知道 JSON,但我必须证明我试过了,哈哈。

谢谢!

更新

import requests


url = '<url>'
params = {'apikey': <key>, 'resource': '<value>'}
response = requests.get(url, params=params)

result = []
with open('C:\\output.json', 'w') as outfile:
  data = response.json()
  for i in data['scans']:
    if (i['detected']=='true'):         // error thrown here
      result.append(i)                  // TypeError: string indices must be integers


print(result)

【问题讨论】:

  • 这看起来不像 JSON...
  • 这是一个yaml文件吗?
  • 不.. 它是一个 JSON 对象
  • JSON 通常有 { } 和 [ ]

标签: python json api


【解决方案1】:

您的原始数据 json 看起来不像 json(查看 json 的样子)。但是假设它被复制错误,以下字典理解将适用于 json:


data = response.json()

with open('C:\\output.json', 'w') as outfile:
    result = {k: v for k, v in data['scans'].items() if v['detected']}
    outfile.write(json.dumps(result))

【讨论】:

    【解决方案2】:
    result =[]
    with open('C:\\output.json', 'w') as outfile:
      data = json.load(outfile)
      for i in data['scans']:
        if i['detected']=='true':
          result.append(i) 
    
    print(result)
    

    【讨论】:

    • 谢谢!我现在收到错误:TypeError: string indices must be integers 通过if (i['detected']=='true'): 行。我相信它正在寻找一个索引,需要类似 [0] 但我不太了解 i 的位置。有关所有内容,请参阅上面的编辑!请并感谢您的帮助!
    猜你喜欢
    • 2020-10-21
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    • 2018-12-08
    • 2017-11-21
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多