【问题标题】:Issues reading json from txt file从 txt 文件读取 json 的问题
【发布时间】:2014-07-11 17:10:44
【问题描述】:

我在一个 txt 文件中有一个 json 字符串,我正在尝试读取它以在之后执行一些其他程序。它看起来像这样:

with open('code test.txt', 'r', encoding=('UTF-8')) as f:
    x = json.load(f)

我知道 json 是有效的,但我得到:

Traceback (most recent call last):
  File "C:\Python33\lib\json\decoder.py", line 368, in raw_decode
    obj, end = self.scan_once(s, idx)
StopIteration

During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 334, in <module>
        user_input()
      File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 328, in user_input
        child_remover()
      File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 280, in child_remover
        x = json.load(f)
      File "C:\Python33\lib\json\__init__.py", line 274, in load
        parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
      File "C:\Python33\lib\json\__init__.py", line 319, in loads
        return _default_decoder.decode(s)
      File "C:\Python33\lib\json\decoder.py", line 352, in decode
        obj, end = self.raw_decode(s, idx=_w(s, 0).end())
      File "C:\Python33\lib\json\decoder.py", line 370, in raw_decode
        raise ValueError("No JSON object could be decoded")
    ValueError: No JSON object could be decoded

我用这个website 来检查字符串是否有效。如果我使用.loads(),我会得到一个不同的错误:

Traceback (most recent call last):
  File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 334, in <module>
    user_input()
  File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 328, in user_input
    child_remover()
  File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 280, in child_remover
    x = json.loads(f)
  File "C:\Python33\lib\json\__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "C:\Python33\lib\json\decoder.py", line 352, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer

原来 json 像这样嵌入到我的脚本中:

json_text="""json stuff here"""

并且没有收到任何错误。关于如何解决这个问题的任何想法???

运行 python 3.3.3 以防万一。

谢谢!!

编辑:

txt 上只是一些随机(有效)json,我遇到了同样的问题。这是我尝试过的操作系统之一:

{"data":
    {"mobileHelp":
        {"value":
            {
            "ID1":{"children": [1,2,3,4,5]},
            "ID2":{"children": []},
            "ID3":{"children": [6,7,8,9,10]}
            }
        }
    }
}

哪一个和 jsonlint.com 一样有效。

【问题讨论】:

  • ValueError: No JSON object could be decoded 暗示该文件包含无效的 JSON。你能用文件内容编辑你的帖子吗?
  • 请将您的文件内容添加到您的问题中。
  • 这些错误表明您的文件在发现 JSON 对象完整之前就已用完。
  • 你可以去jsonlint.com验证你的json。
  • @rodrigocf 我注意到,您的 python 脚本在文件名(包括目录)中包含空格。您可以尝试在路径中没有空格的目录中执行相同的操作吗?加上脚本也是“无空格”的。

标签: python json python-3.x


【解决方案1】:

您的文件在开头包含UTF-8 BOM character。 UTF-8 不需要 BOM,但尤其是 Microsoft 工具坚持要添加一个。

改为使用utf-8-sig 编码打开文件:

>>> open('/tmp/json.test', 'wb').write(b'\xef\xbb\xbf{"data":\r\n    {"mobileHelp":\r\n        {"value":\r\n            {\r\n            "ID1":{"children": [1,2,3,4,5]},\r\n            "ID2":{"children": []},\r\n            "ID3":{"children": [6,7,8,9,10]}\r\n            }\r\n        }\r\n    }\r\n}')
230
>>> import json
>>> with open('/tmp/json.test', encoding='utf8') as f:
...     data = json.load(f)
... 
Traceback (most recent call last):
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/decoder.py", line 367, in raw_decode
    obj, end = self.scan_once(s, idx)
StopIteration

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/__init__.py", line 271, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/__init__.py", line 316, in loads
    return _default_decoder.decode(s)
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/decoder.py", line 351, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/decoder.py", line 369, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
>>> with open('/tmp/json.test', encoding='utf-8-sig') as f:
...     data = json.load(f)
... 
>>> data
{'data': {'mobileHelp': {'value': {'ID2': {'children': []}, 'ID3': {'children': [6, 7, 8, 9, 10]}, 'ID1': {'children': [1, 2, 3, 4, 5]}}}}}

请注意,从 Python 3.4 开始,您会在此处收到更有用的错误消息:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.4/json/__init__.py", line 268, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.4/json/__init__.py", line 314, in loads
    raise ValueError("Unexpected UTF-8 BOM (decode using utf-8-sig)")
ValueError: Unexpected UTF-8 BOM (decode using utf-8-sig)

【讨论】:

  • 完全搞定了,编码解决了它。谢谢!!
【解决方案2】:

不确定第二个错误的代码是什么样的,但看起来您正在传递 json.loads 一个文件对象而不是一个字符串。试试:

with open('code test.txt', 'r', encoding=('UTF-8')) as f:
    x = json.loads(f.read())

或不带换行符:

with open('code test.txt', 'r', encoding=('UTF-8')) as f:
    x = json.loads(f.read().replace('\n', ''))

【讨论】:

  • json.load 接受一个类似文件的对象,json.loads 接受一个字符串。
  • 有了这个我仍然得到“没有json对象可以被解码”
  • 不知道为什么这个答案有两个赞成票,因为它根本没有解决问题; json.load() (no s) 是一个非常有效的加载 JSON 文件的方法,只要文件数据可以被解码并且是正确的。
【解决方案3】:

作为另一种选择,这将更容易解决此问题。

json.loads(open('test.txt').read().decode('utf-8-sig'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多