前段时间,我在json
文件中编写了python词典。今天,我在这个文件中添加了一些其他信息:
with open('path.json', 'a') as fp:
json.dump(DataDict, fp)
尝试使用两种方法打开它:
with open('path.json', 'r') as content_file:
content = content_file.read()
records = json.loads(content)
和
with open('path.json', 'r') as fp:
File = json.load(fp)
但两人都以错误结束:
JSONDecodeError Traceback (most recent call last)
<ipython-input-149-d027cfbf5e86> in <module>()
3 with open('/home/vladislav/Документы/Diploma/data/News/ВТБ.json', 'r') as content_file:
4 content = content_file.read()
----> 5 records = json.loads(content)
/home/vladislav/anaconda3/lib/python3.5/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
317 parse_int is None and parse_float is None and
318 parse_constant is None and object_pairs_hook is None and not kw):
--> 319 return _default_decoder.decode(s)
320 if cls is None:
321 cls = JSONDecoder
/home/vladislav/anaconda3/lib/python3.5/json/decoder.py in decode(self, s, _w)
340 end = _w(s, end).end()
341 if end != len(s):
--> 342 raise JSONDecodeError("Extra data", s, end)
343 return obj
344
JSONDecodeError: Extra data: line 1 column 462852 (char 462851)
我该如何解决?互联网似乎没有第一眼的答案。
答案 0 :(得分:2)
您通过将新的JSON对象连接到它来破坏JSON。也许更好的想法是加载现有数据,扩展它并重新保存它:
import json
DataDict = ...
with open('path.json', 'rb') as fp:
new_data = json.load(fp)
new_data.update(DataDict)
with open('path.json', 'w') as fp:
json.dump(new_data, fp)
根据评论进行修改:
这只是一个想法。如果你一直在连接JSON对象,并假设对象的顶层确实是一个对象(如在{...}
中),那么这个hack可能会起作用:
(注意:请在尝试之前保存并备份此文件!)
import json
with open('path.json', 'rb') as fp:
corrupted = fp.read()
fixed_raw = b", ".join(corrupted.split(b"}{"))
fixed = json.loads(str(fixed_raw, "UTF-8"))
with open('path-fixed.json', 'w') as fp:
json.dump(fixed, fp)