[英]How to parse json file containing list inside a section in python?
我有一個smaple.json,如下所示:
{"Detail":[
{
"DocType":"txt",
"Name":"hello.txt",
}
]}
我需要在“名稱”字段中輸入值。 我在腳本中嘗試如下:
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
因此,我在做錯什么我該如何獲取“名稱”字段詳細信息。
您可以使用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']
錯誤是這一行print val['Name']
。 因為val
是str
類型,所以您不能基於鍵進行查找。
你應該做
ana[0]['Name']
>>> 'hello.txt'
使用json
庫。
import json
with open('sample.json', 'r') as f:
content = json.load(f)
name = content['Detail'][0]['Name']
請在json庫上查看以下鏈接[ https://docs.python.org/2/library/json.html]
/碼
>>> 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'
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.