2017-06-17 97 views
0

假設我有功能,通過一個Python數據結構跨過並返回數據進出口尋找列表格式解析的所有路徑:如何動態地從列表中生成一個JSON路徑

['section', 'section', 'section', 1, 'name', ] 
['section', 'section', 'section', 1] 
['section', 'section'] 

然後我有另一個功能是通過同樣的JSON迭代分析數據

with open(json_file) as data_file: 
json_202 = data.load(data_file) 



def parseJson(*argv) : 
    for arg in argv: 
     #do stuff 

section1 = json_202["section"]["section"]["section"][1]["name"] 
section2 = json_202["section"]["section"]["section"][1] 
section3 = json_202["section"] 

我調用這個函數像這樣:

parseJson(section1, section2, section3) 

什麼是從第一功能動態轉換列表結果到第2個功能,而不是硬楞條section1section2相匹配的格式更Python的方法,section3

+0

將列出的第一個元素始終是JSON的重點對象 –

+0

那麼,什麼叫「JSON」的意思,因爲它看起來像您使用Python列表/類型的字典,而不是JSON,這是一個工作基於文本的序列化格式。 –

+0

是列表中的所有元素都是數據的關鍵,我想要解析的數據 – Darth

回答

0

下面的代碼應執行相同的,但是在其他的方式:

def parse_json_by_path(pathes, data): 
    for path in pathes: 
     item = data 
     for key in path: 
      item = item.get(key) 
     # do stuff 


    parse_json_by_path([["section", "section","section", 1, "name",], 
         ['section', 'section', 'section', 1], 
         ['section', 'section']], json_202) 
+0

謝謝,任何想法爲什麼即時獲取「AttributeError:'列表'對象沒有屬性'獲取'」,當我試圖打印項目? – Darth

相關問題