解决JSON中嵌套键的问题

时间:2017-12-03 22:01:24

标签: json python-2.7

我正在尝试从一个非常棒的网络扫描/图形创建指南中调整一些python代码。

我有使用Onionscan创建的数千个json文件,我有这个代码应该将所有东西都包装在gephi图中。不幸的是,这段代码很旧,因为现在Json文件的格式不同,而且这段代码不再起作用了:

代码(部分):

import glob
import json
import networkx
import shodan

file_list = glob.glob("C:\\test\\*.json")
graph = networkx.DiGraph()

for json_file in file_list:
    with open(json_file,"rb") as fd:
        scan_result = json.load(fd)
        edges = []
        if scan_result('linkedOnions') is not None:
            edges.extend(scan_result['linkedOnions'])

事实上,此时我得到“KeyError”,因为linkedOnions是这样的一级嵌套:

"identifierReport": {
 "privateKeyDetected": false,
  "foundApacheModStatus": false,
  "serverVersion": "",
  "relatedOnionServices": null,
  "relatedOnionDomains": null,
  "linkedOnions": [many urls here]

你可以帮我解决上面的代码吗?

我将非常感激:)

洛伦佐

1 个答案:

答案 0 :(得分:0)

这是读取嵌套JSON的正确方法。

if scan_result['identifierReport']['linkedOnions'] is not None:
            edges.extend(scan_result'identifierReport']['linkedOnions'])

试试这个,如果您的JSON文件格式正确

,它将适用于您
try:
   scan_result = json.load(fd)
   edges = []
   if scan_result('linkedOnions') is not None:
      edges.extend(scan_result['linkedOnions'])
except Exception,e:
     #print your message or log
     print e
相关问题