【问题标题】:How to iterate through json object for all key value pairs of specific fields?如何遍历特定字段的所有键值对的json对象?
【发布时间】:2019-11-11 00:02:19
【问题描述】:

我有这个 json 响应

{   "assets": [
    {
      "id": 518447,
      "created_at": "2019-09-10T10:13:38Z",
      "priority": 10,
      "operating_system": "Microsoft - Windows - Windows Server 2008 R2, Enterprise Edition - SP1",
      "notes": null,
      "last_booted_at": null,
      "primary_locator": "external_id",
      "locator": "1112359",
      "vulnerabilities_count": 22,
      "status": "active",
      "last_seen_time": "2019-09-08T16:00:17Z",
      "network_ports": [
        {
          "id": 33550493,
          "port_number": 180,
          "extra_info": "",
          "hostname": null,
          "name": "HTTP",
          "ostype": "",
          "product": "JBoss EAP",
          "protocol": "tcp",
          "state": "open",
          "version": "4.2.3.GA"
        },
        {
          "id": 33550494,
          "port_number": 100,
          "extra_info": "",
          "hostname": null,
          "name": "SNMP",
          "ostype": "",
          "product": null,
          "protocol": "udp",
          "state": "open",
          "version": null
        },

      ],
      "tags": [
        "Windows Server",
        "DO - DO SPG BOM"
      ],
      "owner": null,
      "urls": {
        "vulnerabilities": ""
      },
      "ip_address": "10.10.10.1",
      "database": null,
      "hostname": null,
      "fqdn": null,
      "netbios": null,
      "application": null,
      "file": null,
      "mac_address": null,
      "ec2": null,
      "url": null,
      "external_id": "1112359",
      "ipv6": null,
      "asset_groups": [
        {
          "id": 4,
          "name": "0 Global - All"
        },
        {
          "id": 204,
          "name": "DO - All"
        },
        {
          "id": 417,
          "name": "Do - All"
        }
      ]
    }

我已经通过第一个索引 [0] 尝试过,但我知道有更好的方法来解决这个问题

 import request
import json

url = 'https://thisismyurl.com/assets/'
token = 'blahblah'
headers = {'X-Risk-Token': token, 'Accept': 'application/json'}
response = requests.get(url,headers=headers)
print(response.status_code)
json_format = json.loads(response.text)
for a in  json_format['assets']:
     for key, value in json_format:
print('operating_system : ' + json_format['assets'][0]['operating_system'] + ' , ' + 'ip_address : ' + json_format['assets'][0]['ip_address'] + 'tags : ' + json_format['assets'][0]['tags'])

但我的方式并没有产生我想要的预期输出。

我只想通过整个 json 找到每个出现的操作系统、IP 地址和标签

我想要的输出是:

"operating_system": "Microsoft - Windows - Windows Server 2008 R2, Enterprise Edition - SP1", "tags":  "Windows Server" "DO - DO SPG BOM" , "ip_address": "10.10.10.1".

我如何用 Python 做到这一点?

【问题讨论】:

  • "但是我的方式并没有产生我想要的预期输出。"你可以说得更详细点吗?另外,我尝试解析您在上面共享的 JSON 示例,但出现解码器错误。
  • JSON 示例中似乎缺少一些字符。此外,您的 print('operating system.... 行似乎没有正确缩进,尽管我不知道这是您的代码中的问题还是只是添加到您的帖子中的方式。
  • @AlexanderCécile 我打印出来的只是每个特定字段的第一个索引print('operating_system : ' + json_format['assets'][0]['operating_system'] 只打印我想要遍历整个 json 的第一次出现
  • 看我的回答:)
  • 我更新的答案对你有用吗?

标签: python json api


【解决方案1】:

您的代码中有多个部分可能会导致该错误。我写了一些代码,给出了适当的结果,唯一的区别是我从文件中读取 JSON。

代码:

import json
import csv

with open('../resources/web_json_test.json', 'r') as file_1:
    json_res: dict = json.loads(file_1.read())

with open('../out/json_to_csv_out.csv', 'w', newline='') as file_1:
    csv_writer = csv.DictWriter(file_1, fieldnames=['operating_system', 'tags', 'ip_address'])
    csv_writer.writeheader()
    for curr in json_res['assets']:
        csv_writer.writerow(
            {'operating_system': curr["operating_system"], 'tags': curr["tags"], 'ip_address': curr["ip_address"]})

输出:

操作系统、标签、IP地址
"Microsoft - Windows - Windows Server 2008 R2, Enterprise Edition - SP1","['Windows Server', 'DO - DO SPG BOM']",10.10.10.1

【讨论】:

  • 感谢您的回复!它帮助很大
  • @Xfactor 不客气!如果它令人满意地回答了您的问题,您可以mark it as accepted
  • 出于好奇,我确实有一个问题,如果我想将此打印语句写入 csv,我是否必须将特定字段与它们的出现分开?
  • @Xfactor 你要为每个写操作系统、标签和ip吗?
  • 是的,例如我在 csv 文件```Microsoft - Windows - Windows Server 2008 R2, Enterprise Edition - SP1 |标签: ['Windows Server', 'DO - DO SPG BOM'] | ip地址:10.10.10.1```
猜你喜欢
  • 2017-06-07
  • 1970-01-01
  • 2014-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多