【问题标题】:JSON object must be str, not 'bytes'JSON 对象必须是 str,而不是 'bytes'
【发布时间】:2016-02-04 04:46:24
【问题描述】:

使用 Python 3.5.1,我拉入了一个文本文件,其中每一行都是 JSON 格式: {"a":"windows", "b":"stairs"...}

import json
path = 'folder/data.txt'
records=[json.loads(line) for line in open(path,'rb')]

但我收到了错误:

the JSON object must be str, not 'bytes'

我打印文件的第一行没有问题,所以我确信文件路径是正确的。

【问题讨论】:

  • 也许可以去掉open 通话中的“b”? docs.python.org/2/library/functions.html#open 表示将以二进制形式加载文件,这可能是它不被视为字符串的原因。
  • 如果你只取文件的一行,你能把它加载到json吗?喜欢json.loads(file.readlines()[0])
  • @TW80000 你的建议解决了我的问题。我还了解到直接在open 调用中传递encoding='utf-8' 也可以。感谢您的评论。

标签: python json text import


【解决方案1】:

以文本模式打开文件,而不是二进制模式(可能显式传递 encoding='utf-8' 以覆盖系统默认值,因为 JSON 通常存储为 UTF-8)。 json 模块只接受str 输入;从以二进制模式打开的文件中读取返回 bytes 对象:

# Using with statement just for good form; in this case it would work the
# same on CPython, but on other interpreters or different CPython use cases,
# it's easy to screw something up; use with statements all the time to build good habits
with open(path, encoding='utf-8') as f:
    records=[json.loads(line) for line in f]

【讨论】:

  • 这很有效,感谢您提供有关使用正确表格的建议。在我的原始代码中为 'encoding='utf-8' 切换 'rb' 似乎也可以。
【解决方案2】:

尝试: records=[json.loads(line.decode()) for line in open(path,'rb')]

【讨论】:

    【解决方案3】:

    您不想指定“rb”,因为 JSON 模块无法读取文件的二进制表示。您可能需要“utf-8”编码和“读取”。编辑:我最初说过这两个都是默认值,但我注意到许多操作系统具有不同的默认编码,并且 Python 在 open() 中使用系统设置作为默认值。因此,我建议将编码设置明确提供为“utf-8”。

    json 支持使用“json.load”而不是“json.loads”从打开的文件中加载,后者从字符串中加载,因此我们可以跳过作为文本读取的内容并直接转到 JSON。我认为您不会想要“加载”单个行,因为这可能不是有效的 JSON。

    import json
    # open has __enter__ and __exit__ functions, so we can call it as a guard
    # using "with" syntax and it'll close when the scope ends
    with open(r".\myjson.json", encoding="utf-8") as fh:
        # load() is a convenience function to help us avoid iterating lines
        # on our own. It calls loads() on the whole doc and returns an obj
        json_obj = json.load(fh)
    print (json_obj)
    

    【讨论】:

    • UTF-8 并不总是默认的encoding、it's determined dynamically from platform dependent settings using locale.getpreferredencoding(False)。如果您知道输入是 UTF-8,请明确说明。类似地,如果有人每行编写一个 JSON blob,您不能一次加载整个文件,因为整个文件加在一起不是有效的 JSON,这些行只是孤立的合法 JSON。另外,json.load 只是调用file.read() 并传递给loads,所以它既不比loads 好也不差。此外,Py3 print 需要括号。
    • 优点,@ShadowRanger。对于 load() 与 load(),我并不是要暗示这里存在性能差距,而是有一个 for 循环,我们不需要在自己的代码中编写/读取/维护它。使用 load() 噪音更小,这通常是 Pythonic 做事的方式。印刷品是我在 2.7 的解释器中工作(我的坏和固定的)。 UTF-8 认为你是完全正确的,我应该在 Windows 上作为开头(不一定是 OP 的情况)。
    • 实际上,在 Windows 上,我不认为 UTF-8 是默认的,它通常是 Windows 代码页之一(例如 cp1252,它是 latin-1 的变体,它替换了一些通常未使用的带有附加可打印字符的控制字符,例如智能引号)。如果数据都是 ASCII,那么无论哪种方式都可以(UTF-8 和 cp1252 都是 ASCII 超集),只有当您超出 ASCII 范围时才会遇到问题。除了代码页之外,Windows 通常对所有内容都使用 UTF-16。它只在处理 Internet 上的数据时接受 UTF-8(其中 UTF-8 是标准)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 2017-08-31
    • 2023-03-13
    • 2023-03-29
    • 2021-06-17
    • 2017-11-01
    • 2018-08-17
    相关资源
    最近更新 更多