Skip to content Skip to sidebar Skip to footer

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. It looks like this: with open('code test.txt', 'r', encoding=('UTF-8')) as f:

Solution 1:

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.

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
>>> withopen('/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
>>> withopen('/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:

Traceback (most recent calllast):
  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)

Solution 2:

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. Try:

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

or without newlines with:

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

Solution 3:

As another choice, This will be much easier to fix this issue.

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

Post a Comment for "Issues Reading Json From Txt File"