首页 > 解决方案 > json.load 和 json.loads 无法加载 JSON 文件数据,Python

问题描述

请查看以下 JSON 文件,我一直在尝试阅读:

    [
        {
            "age": "['3']",
            "description": " Depending on the last time your little one was fed ",
            "schedule": "Milk Feed",
            "time": "6:15 am"
        },
        {
            "age": "['3']",
            "description": " Someone's feeling a bit sleepy!",
            "schedule": "Naptime",
            "time": "8:15 am - 9:15 am"
        }
    ][
        {
            "age": "['4']",
            "description": " Depending on the last time your little one was fed ",
            "schedule": "Milk Feed",
            "time": "6:15 am"
        },
        {
            "age": "['4']",
            "description": " Someone's feeling a bit sleepy!",
            "schedule": "Naptime",
            "time": "8:15 am - 9:15 am"
        }
    ]

我已经尝试过JSON.load, 和JSON.loads

用 json.load

AttributeError: 'str' object has no attribute 'read'

并使用 json.loads,我收到以下输出

raise JSONDecodeError("Expecting value", s, err.value) from None

这是我的代码

    for line in open('baby_schedule.json', 'r'):
        print(json.loads(line))

我需要你的帮助来加载这个 JSON,然后读取其中的单个项目。

标签: pythonjson

解决方案


您的 json 无效。
这是正确的版本。

您应该使用json.loads缓冲区和json.load文件

[
  {
    "age": "['3']",
    "description": " Depending on the last time your little one was fed ",
    "schedule": "Milk Feed",
    "time": "6:15 am"
  },
  {
    "age": "['3']",
    "description": " Someone's feeling a bit sleepy!",
    "schedule": "Naptime",
    "time": "8:15 am - 9:15 am"
  },
  {
    "age": "['4']",
    "description": " Depending on the last time your little one was fed ",
    "schedule": "Milk Feed",
    "time": "6:15 am"
  },
  {
    "age": "['4']",
    "description": " Someone's feeling a bit sleepy!",
    "schedule": "Naptime",
    "time": "8:15 am - 9:15 am"
  }
]

推荐阅读