简体   繁体   English

从txt文件读取json时出现问题

[英]Issues reading json from txt file

I have a json string in a txt file and I'm trying to read it to do some other procedures afterwards. 我在txt文件中有一个json字符串,后来我试图读取它以执行其他一些步骤。 It looks like this: 看起来像这样:

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

I know the json is valid, but I'm getting: 我知道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

I used this website to check if the string is valid. 我使用此网站检查字符串是否有效。 If I use .loads() , I get a different error: 如果使用.loads().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

Originally the json was embeded in my script like this: 最初,json像这样嵌入到我的脚本中:

json_text="""json stuff here"""

And didn't get any errors. 而且没有任何错误。 Any ideas on how to fix this??? 有想法该怎么解决这个吗???

Running python 3.3.3 just in case. 以防万一,运行python 3.3.3。

Thanks!! 谢谢!!

EDIT: 编辑:

Just some random (valid) json on the txt and I get the same issue. txt上只有一些随机(有效)的json,我也遇到了同样的问题。 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]}
            }
        }
    }
}

Which is valid as well as per jsonlint.com. 与jsonlint.com一样有效。

Your file contains a UTF-8 BOM character at the start. 您的文件开头包含一个UTF-8 BOM字符 UTF-8 doesn't need a BOM but especially Microsoft tools insist on adding one anyway. UTF-8 不需要BOM,但特别是Microsoft工具始终坚持添加BOM

Open the file with the utf-8-sig encoding instead: 而是使用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]}}}}}

Note that from Python 3.4 onwards you get a more helpful error message here: 请注意,从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)

Not sure what your code looks like for the second error, but it looks like you are passing json.loads a file object and not a string. 不确定第二个错误的代码是什么样子,但是好像您正在传递json.loads是文件对象,而不是字符串。 Try: 尝试:

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

or without newlines with: 或没有换行符:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM