问题
I want to fetch the output of below json file using python
Json file
{
"Name": [
{
"name": "John",
"Avg": "55.7"
},
{
"name": "Rose",
"Avg": "71.23"
},
{
"name": "Lola",
"Avg": "78.93"
},
{
"name": "Harry",
"Avg": "95.5"
}
]
}
I want to get the average marks of the person, when I look for harry i.e. I need output in below or similar format
Harry = 95.5
Here's my code
import json
json_file = open('test.json') //the above contents are stored in the json
data = json.load(json_file)
do = data['Name'][0]
op1 = do['Name']
if op1 is 'Harry':
print do['Avg']
But when I run I get error IOError: [Errno 63] File name too long
.
回答1:
How to print the score of Harry with python 3
import json
from pprint import pprint
with open('test.json') as data_file:
data = json.load(data_file)
for l in data["Name"]:
if (str(l['name']) == 'Harry'):
pprint(l['Avg'])
回答2:
You can do something simple like this
import json
file = open('data.json')
json_data = json.load(file)
stud_list = json_data['Name']
y = {}
for var in stud_list:
x = {var['name']: var['Avg']}
y = dict(list(x.items()) + list(y.items()))
print(y)
It gives the output in dictionary format
{'Harry': '95.5', 'Lola': '78.93', 'Rose': '71.23', 'John': '55.7'}
回答3:
json.load loads data from file file-like
object. If you want to read it from string you may use json.loads
.
来源:https://stackoverflow.com/questions/39492541/read-json-file-and-get-output-values