简体   繁体   English

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

[英]How to parse json file containing list inside a section in python?

I have a smaple.json as follows: 我有一个smaple.json,如下所示:

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

I need to have the value aginst the "Name" Field. 我需要在“名称”字段中输入值。 i tried in my script as follows: 我在脚本中尝试如下:

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']

and i get output as : 我得到的输出为:

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

So what am i doing wrong how shall i get the "Name" field details. 因此,我在做错什么我该如何获取“名称”字段详细信息。

You could use the json library: 您可以使用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']

error is at this line print val['Name'] . 错误是这一行print val['Name'] Because val is str type so you can't lookup on key basis. 因为valstr类型,所以您不能基于键进行查找。

You should do 你应该做

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

Use json library. 使用json库。

import json

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

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

Please see the below link on json library [ https://docs.python.org/2/library/json.html] 请在json库上查看以下链接[ https://docs.python.org/2/library/json.html]

  1. open the json file 打开json文件
  2. use json.loads() to decodethe data. 使用json.loads()解码数据。
  3. access it with headers 用标题访问它

/code /码

>>> 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