【问题标题】:How to read json file in python?如何在python中读取json文件?
【发布时间】:2019-07-12 02:24:29
【问题描述】:

我刚开始学习 JSON,我想从我的电脑上读取一个 JSON 文件。

我用json.loads() 尝试过这个,我得到这个错误:json.decoder.JSONDecodeError: Expecting ',' delimiter: line 9 column 20 (char 135)

所以我尝试使用open()从我的 PC 加载 JSON 文件中的数据,但我发现它没有返回字符串类型的输出,并且它给出了错误:TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper

然后我尝试使用read() 并给出错误:json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

我试过这些:

1)

with open('FILE.json') as f:
        data = json.loads(f.read())

2)

with open('FILE.json') as f:
        data = json.loads(f)

3)

with open('FILE.json', 'r', encoding='utf-8') as f:
          data = json.loads(f.read())

【问题讨论】:

  • error Expecting value: line 1 column 1 (char 0) 表示您从空文件中读取。它无法解码空字符串。最好检查您在此文件中的内容。或者您可能从不同的文件中读取数据。
  • @furas 那只是表示文件格式不正确。
  • @furas, @aero blue 在这种情况下,文件已被读取。在每次读取之间,需要重新打开文件或需要使用f.seek(0) 回到开头。
  • 尽管line 9 column 20 (char 135),您的问题确实是第一个错误。这表明您需要修复 JSON 文件中的格式错误,如果格式正确,您的第一个示例实际上将正确读取 JSON。

标签: python json python-3.x


【解决方案1】:

基于阅读documentation

试试这个:

with open(absolute_json_file_path, encoding='utf-8-sig') as f:
    json_data = json.load(f)
    print(json_data)

【讨论】:

    【解决方案2】:

    您想使用json.load() 而不是json.loads()

    例子:

     with open(file.json) as f:
    
          x = json.load(f)
    

    【讨论】:

      猜你喜欢
      • 2021-10-21
      • 2017-12-24
      • 1970-01-01
      • 2018-02-27
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      • 2018-10-14
      相关资源
      最近更新 更多