简体   繁体   中英

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

I have a smaple.json as follows:

{"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:

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'] . Because val is str type so you can't lookup on key basis.

You should do

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

Use json library.

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]

  1. open the json file
  2. use json.loads() to decodethe data.
  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'
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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