Reputation: 33
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.
Upvotes: 1
Views: 2382
Reputation: 166
Please see the below link on json library [https://docs.python.org/2/library/json.html]
/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'
>>>
Upvotes: 0
Reputation: 1653
Use json
library.
import json
with open('sample.json', 'r') as f:
content = json.load(f)
name = content['Detail'][0]['Name']
Upvotes: 0
Reputation: 690
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']
Upvotes: 2
Reputation: 5061
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'
Upvotes: 0