2015-11-03 67 views
3

我正在嘗試編寫一個腳本,以點表示形式打印JSON文件的唯一鍵以便快速剖析結構。使用Python在點表示法中打印獨特的JSON鍵

例如,讓我們說我有「myfile.json」具有以下格式:

{ 
"a": "one", 
"b": "two", 
"c": { 
    "d": "four", 
    "e": "five", 
    "f": [ 
     { 
      "x": "six", 
      "y": "seven" 
     }, 
     { 
      "x": "eight", 
      "y": "nine" 
     } 
    ] 
} 

運行下面會產生獨特的一套鑰匙,但它缺少的血統。以下輸出不表示'x','y'嵌套在'f'數組中。

a 
b 
c 
d 
e 
f 
x 
y 

我想不出如何遍歷嵌套結構來追加父鍵。

理想的輸出將是:

a 
b 
c.d 
c.e 
c.f.x 
c.f.y 
+0

你已經在'get_keys'中對字典做了很好的遍歷,爲什麼不在函數內部打印呢? –

回答

0

我建議使用遞歸生成功能,採用產量語句,而不是在內部建立一個列表。在Python 2.6+,以下工作:

import json 
json_data = json.load(open("myfile.json")) 

def walk_keys(obj, path=""): 
    if isinstance(obj, dict): 
     for k, v in obj.iteritems(): 
      for r in walk_keys(v, path + "." + k if path else k): 
       yield r 
    elif isinstance(obj, list): 
     for i, v in enumerate(obj): 
      s = "[" + str(i) + "]" 
      for r in walk_keys(v, path + s if path else s): 
       yield r 
    else: 
     yield path 


for s in sorted(walk_keys(json_data)): 
    print s 

在Python 3.x中,你可以使用收益率從爲遞歸生成語法糖,具體如下:

import json 
json_data = json.load(open("myfile.json")) 

def walk_keys(obj, path=""): 
    if isinstance(obj, dict): 
     for k, v in obj.items(): 
      yield from walk_keys(v, path + "." + k if path else k) 
    elif isinstance(obj, list): 
     for i, v in enumerate(obj): 
      s = "[" + str(i) + "]" 
      yield from walk_keys(v, path + s if path else s) 
    else: 
     yield path 


for s in sorted(walk_keys(json_data)): 
    print(s) 
+0

這工作出色! – T3X45

0

抽出的MTADD的指導我總結了以下:

import json 

json_file_path = "myfile.json" 
json_data = json.load(open(json_file_path)) 

def walk_keys(obj, path = ""): 
    if isinstance(obj, dict): 
     for k, v in obj.iteritems(): 
      for r in walk_keys(v, path + "." + k if path else k): 
       yield r 
    elif isinstance(obj, list): 
     for i, v in enumerate(obj): 
      s = "" 
      for r in walk_keys(v, path if path else s): 
       yield r 
    else: 
     yield path 

all_keys = list(set(walk_keys(json_data))) 

print '\n'.join([str(x) for x in sorted(all_keys)]) 

結果匹配預期

a 
b 
c.d 
c.e 
c.f.x 
c.f.y