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

时间:2018-06-13 05:03:03

标签: python json database python-2.7

我有一个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中的scans标记中提取所有非空结果(所有非空结果)并将其存储到数据库的表列中的单个逗号分隔字符串中?

谢谢!

2 个答案:

答案 0 :(得分: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))

答案 1 :(得分:1)

回复真的是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加载到python dict后,您可以执行以下操作。

import json

jsonDict = json.loads(yourJSON)

results = []
for scanElement in jsonDict['scans']:
    if scanElement['result'] != None:
        results.append(scanElement['result'])

##save the results to your DB