繁体   English   中英

如何在python的一个部分中解析包含列表的json文件?

[英]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'] 因为valstr类型,所以您不能基于键进行查找。

你应该做

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]

  1. 打开json文件
  2. 使用json.loads()解码数据。
  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'
>>> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM