2017-07-11 13 views
1

我有一個smaple.json如下:如何解析包含列表中的列表在python中的部分內的json文件?

{"Detail":[ 
    { 
    "DocType":"txt", 
    "Name":"hello.txt", 
    } 
    ]} 

我需要有aginst「名稱」字段的值。我想在我的腳本如下:

file="c:/sample.json" 
for list in file: 
    if (str(list['Detail'])=='None'): 
     print("Do nothing") 
    else: 
     ana = list['Detail'] 
     val = (str(ana)[1:-1]) 
     print val 
     print val['Name'] 

,我也得到輸出:

{"DocType":"txt","Name":"hello.txt"} 
    error:print (ana['Name']) 
    TypeError: string indices must be integers 

那我做錯了應如何我得到的「名稱」字段的細節。

+0

你正在處理一個JSON對象爲一個字符串,它是不是一個好的做法訪問它。嘗試將其作爲字典處理,然後訪問您想要的元素。這看起來也很容易。 –

回答

2

您可以使用json庫:

import json 

json_path = "c:\\sample.json" 
with open(json_path) as json_file: 
    json_dict = json.load(json_file) 

name = json_dict['Detail'][0]['Name'] 
0

錯誤在於此行print val['Name']。因爲valstr類型,所以你不能在關鍵基礎上查找。

你應該做

ana[0]['Name'] 
>>> 'hello.txt' 
0

使用json庫。

import json 

with open('sample.json', 'r') as f: 
    content = json.load(f) 

name = content['Detail'][0]['Name'] 
0

請參閱JSON庫下面的鏈接[https://docs.python.org/2/library/json.html]

  1. 打開JSON文件
  2. 使用json.loads()來decodethe數據。
  3. 頁眉

/代碼

>>> import json 
>>> with open('test.json','r') as e: 
...  data = json.loads(e.read()) 
... 
>>> data 
{u'Detail': [{u'DocType': u'txt', u'Name': u'hello.txt'}]} 
>>> data['Detail'][0]['Name'] 
u'hello.txt' 
>>> 
相關問題