读取json文件并获取输出值(Read json file and get output values)

367 IT屋

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.

解决方案

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

我想使用python获取以下json文件的输出



Json文件



  {
Name:[
{
name: John,
Avg: 55.7
},
{
name: Rose,
Avg: 71.23
},
{
name: Lola,
Avg: 78.93
},
{
name: Harry,
Avg: 95.5
}

]
}


当我寻找哈利
时,我想获得该人的平均分数,即我需要以以下或类似格式输出



哈里= 95.5



这是我的代码



  import json 

json_file = open('test.json')//以上内容存储在json
data = json.load(json_file)
做=数据['名称' ] [0]
op1 = do ['Name']
,如果op1是'Harry':
print do ['Avg']
< / pre>

但是当我运行时,出现错误 IOError:[Errno 63]文件名太长。


解决方案

您可以执行以下简单操作



  import json 

file = open('data.json')
json_data = json.load(file)

stud_list = json_data ['Name ']
y = {}
for stud_list中的var:
x = {var ['name']:var ['Avg']}
y = dict(list(x.items ())+ list(y.items()))

print(y)


它以字典格式给出输出



{'Harry':'95 .5','Lola':'78 .93','Rose':'71 .23' ,约翰: 55.7}


本文地址:IT屋 » 读取json文件并获取输出值