Python将JSON响应的一部分存储为逗号分隔的字符串

2024-09-30 00:25:06 发布

您现在位置:Python中文网/ 问答频道 /正文

来自多个站点的JSON扫描结果包含来自多个反病毒站点的字符串I。看起来像-

"scans": {
  "Bkav": {
    "detected": false,
    "version": "1.3.0.9466",
    "result": null,
    "update": "20180609"
  },
  "MicroWorld-eScan": {
    "detected": true,
    "version": "14.0.297.0",
    "result": "W97M.Downloader.AIU",
    "update": "20180611"
  },
  "CMC": {
    "detected": false,
    "version": "1.1.0.977",
    "result": null,
    "update": "20180610"
  },
  "CAT-Quickheal": {
    "detected": true,
    "version": "14.00",
    "result": "X97M.Dropper.PD",
    "update": "20180611"
  },
  "McAfee": {
    "detected": true,
    "version": "6.0.6.653",
    "result": "X97M/Downloader.asi",
    "update": "20180611"
  },
},
"tags": {
...
},

如何从这个JSON中的scans标记提取所有非空结果(所有非空的结果),并将其存储到数据库表列中的一个逗号分隔的字符串中?在

谢谢!在


Tags: 字符串jsonfalsetrue站点versionupdatedownloader
2条回答

可能有一种更有效的方法,但我认为这应该会给你一个逗号分隔的字符串值:

import json

scans = response_data.get('scans', [])
scan_results = (scans[key]['result'] for key in scans.keys())
csv = ', '.join((result for result in scan_results if result is not None))

响应真的是JSON吗? 我知道,JSON不能用分号分隔。 应该像下面这样。在

"scans": {
  "Bkav": {
    "detected": false,
    "version": "1.3.0.9466",
    "result": null,
    "update": "20180609"
  },
  "MicroWorld-eScan": {
    "detected": true,
    "version": "14.0.297.0",
    "result": "W97M.Downloader.AIU",
    "update": "20180611"
  },
  "CMC": {
    "detected": false,
    "version": "1.1.0.977",
    "result": null,
    "update": "20180610"
  },
  "CAT-Quickheal": {
    "detected": true,
    "version": "14.00",
    "result": "X97M.Dropper.PD",
    "update": "20180611"
  },
  "McAfee": {
    "detected": true,
    "version": "6.0.6.653",
    "result": "X97M/Downloader.asi",
    "update": "20180611"
  },
},
"tags": {
...
},

将JSON加载到pythondict之后,可以执行如下操作。在

^{pr2}$

相关问题 更多 >

    热门问题