2017-06-19 19 views
0

我有一個複雜的JSON文件,由多個嵌入式列表和字典組成。在這個文件的某處,有一個元素「ABC」:它可以是一個列表元素,鍵或值。我可以使用哪種方法搜索文件以查找此元素的索引?什麼是在Python中複雜的json文件中查找元素(鍵或值)索引的最佳方法?

例子:

{"Record": 
    {"RecordType": "No", 
    "RecordNumber": 11, 
    "Section": [ 
     { 
     "Heading": "Structure", 
     "Description": "Compound", 
     "Information": [ 
      { 
      "ReferenceNumber": 88, 
      "Name": "2D Structure", 
      "BoolValue": true 
      } 
     ] 
     },]}} 

我想尋找2D Structure和安裝Python回報: {"Record"}{"Section"}[0]{"Information"}[0]{"Name"}

我試圖搜索一些「反向詞典」 - 我可以在這裏解析一個字符串,返回一個位置,但沒有找到任何可行的東西。但也許有一些簡單的解決方案?

+0

你必須遍歷_JSON_(加載字典),並做匹配自己。 – CristiFati

+1

遞歸是你的朋友在這裏。 –

回答

2

我會假設你已經deseralized你的JSON轉換爲Python對象:

import json 
with open('path/to/my.json') as f: 
    obj = json.load(f) 

現在,「最簡單」的解決方法是窮舉搜索整個嵌套結構。這是我熟練的一個快速功能,就是這麼做的。這不是很有效的,但是它的工作原理:

def search_nested(obj, target, acc): 
    if isinstance(obj, list): 
     for i, e in enumerate(obj): 
      if isinstance(e, (list, dict)): 
       x = search_nested(e, target, acc + [i]) 
       if x: 
        return x 
      elif e == target: 
       return acc + [i] 
    elif isinstance(obj, dict): 
     for k, v in obj.items(): 
      if target == v: 
       return acc + [k] 
      elif target == k: #how do you want to handle this? 
       return acC# Maybe? 
      elif isinstance(v, (list, dict)): 
       x = search_nested(v, target, acc +[k]) 
       if x: 
        return x 

所以,在REPL:

In [3]: obj 
Out[3]: 
{'Record': {'RecordNumber': 11, 
    'RecordType': 'No', 
    'Section': [{'Description': 'Compound', 
    'Heading': 'Structure', 
    'Information': [{'BoolValue': True, 
     'Name': '2D Structure', 
     'ReferenceNumber': 88}]}]}} 

In [4]: search_nested(obj, "2D Structure", []) 
Out[4]: ['Record', 'Section', 0, 'Information', 0, 'Name'] 
相關問題