【问题标题】:Read json file and get output values读取 json 文件并获取输出值
【发布时间】:2017-01-22 09:12:47
【问题描述】:

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

Json 文件

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

    ]
}

我想得到这个人的平均分,当我找 harry 即我需要以下或类似格式的输出

Harry = 95.5

这是我的代码

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

但是当我运行我得到错误IOError: [Errno 63] File name too long

【问题讨论】:

  • json 是从哪里来的?你试过什么
  • 你需要展示你已经尝试过的东西,没有人在这里为你编写所有代码。如果您可以编辑以显示您尝试过的内容和无效的内容,我们可以为您提供帮助。已经有很多关于在 Python 中处理 JSON 的问题和答案。
  • 抱歉信息不完整,我是这个论坛的新手,这是我的代码
  • 感谢 cmets,我已经通过将内容转换为 dict 类型并获得所需格式的输出来解决问题

标签: python json ioerror


【解决方案1】:

如何用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】:

    json.load 从文件file-like 对象加载数据。如果你想从字符串中读取它,你可以使用json.loads

    【讨论】:

      【解决方案3】:

      你可以做一些像这样简单的事情

      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)
      

      它以字典格式给出输出

      {'Harry': '95.5', 'Lola': '78.93', 'Rose': '71.23', 'John': '55.7'}
      

      【讨论】:

        猜你喜欢
        • 2022-11-27
        • 2017-08-05
        • 1970-01-01
        • 2022-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-04
        • 1970-01-01
        相关资源
        最近更新 更多