从txt文件读取json时出现问题 [英] Issues reading json from txt file

查看:154
本文介绍了从txt文件读取json时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在txt文件中有一个json字符串,之后我试图读取它以执行其他一些步骤.看起来像这样:

I have a json string in a txt file and I'm trying to read it to do some other procedures afterwards. It looks like this:

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

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

I know the json is valid, but I'm getting:

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

我使用了这个网站来检查字符串是否有效.如果使用.loads(),则会收到其他错误:

I used this website to check if the string is valid. If I use .loads(), I get a different error:

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嵌入到我的脚本中,如下所示:

Originally the json was embeded in my script like this:

json_text="""json stuff here"""

并且没有得到任何错误.关于如何解决此问题的任何想法?

And didn't get any errors. Any ideas on how to fix this???

运行python 3.3.3以防万一.

Running python 3.3.3 just in case.

谢谢!

在txt上只是一些随机(有效)的json,我遇到了同样的问题.这是我尝试过的其中之一:

Just some random (valid) json on the txt and I get the same issue. This os one of the ones i tried:

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

与jsonlint.com一样有效.

Which is valid as well as per jsonlint.com.

推荐答案

您的文件包含开头是UTF-8 BOM字符. UTF-8 不需要BOM ,但特别是Microsoft工具仍然坚持要添加BOM.

Your file contains a UTF-8 BOM character at the start. UTF-8 doesn't need a BOM but especially Microsoft tools insist on adding one anyway.

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

Open the file with the utf-8-sig encoding instead:

>>> 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开始,您会在此处获得更有用的错误消息:

Note that from Python 3.4 onwards you get a more helpful error message here:

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)

这篇关于从txt文件读取json时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆