【问题标题】:"TypeError: the JSON object must be str, not 'bytes'" reading JSON in Python 3.5“TypeError:JSON 对象必须是 str,而不是 'bytes'”在 Python 3.5 中读取 JSON
【发布时间】:2017-11-01 16:08:47
【问题描述】:

我想运行以下代码,最初是为 Python 2.7 编写的,现在我想为 python3.5 运行。 以下是我的代码:

import json
import glob

read_files = glob.glob("*.json")
output_list = []

for f in read_files:
    with open(f, "r") as infile:
       output_list.append(json.load(infile))

with open("merged_file.json", "wb") as outfile:
    json.dump(output_list, outfile)

但它一直给出以下错误:

         raise JSONDecodeError("Expecting value", s, err.value) from 
None
 json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

json.loadjson.loads 之间有什么区别,我如何确定何时使用哪个?

【问题讨论】:

  • 删除open ("rb" -> "r") 中的二进制模式。我不知道你为什么把它放在那里。
  • 您可以将文件读取为字符串而不是二进制模式

标签: python json python-2.7 python-3.5


【解决方案1】:

将您的 open(f, "rb") 更改为 open(f, "r")。 rb 标志用于读取字节。

【讨论】:

  • 当我更改它时,会出现此错误:从无 json.decoder.JSONDecodeError 引发 JSONDecodeError("Expecting value", s, err.value): Expecting value: line 1 column 1 (字符 0)
  • 使用json.loads加载字符串
猜你喜欢
  • 1970-01-01
  • 2023-03-13
  • 2019-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-11
  • 2019-10-10
  • 1970-01-01
相关资源
最近更新 更多