Skip to main content
 首页 » 编程设计

python之JSON 解码字符串之未终止的字符串

2025年05月04日11jpfss

我有一个 2 GB 的 json 文件,当我尝试加载它时出现此错误:

json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 1093156512 (char 1093156511)

所以这意味着可能有一些 escape sequence ,对吗?(或类似的东西..)弄乱了 json 正确吗?问题是这个文件很大,只是在编辑器中打开它是一个巨大的痛苦。在我看到问题所在之前,编辑器 100% 崩溃了。但是,我仍然需要以某种方式解决这个问题......我不确定是什么导致了这个问题......可能有很多原因。

我的数据本质上是一个对象列表,如下所示:

data = [{key1: 123, key2:"this is the first string to concatenate"}, 
 {key1: 131, key2:"this is the second string to concatenate"}, 
 {key1: 152, key2:"this is the third string to concatenate"} ]  

除了更复杂的key2。如果问题是 \,如果我去掉 json 文件中的所有 \,它会起作用吗?但是,没有什么可以说奇怪的转义字符是我的问题....另外,我对我的输入 json 文件是什么几乎没有控制,所以我认为我无论如何都无法改变它。

有没有办法在不更改输入 json 文件的情况下解决这个问题?

[编辑] 这是整个错误跟踪:

File "halp.py", line 38, in data = json.load(json_file,strict=False)

File "/usr/lib/python3.6/json/init.py", line 299, in load parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)

File "/usr/lib/python3.6/json/init.py", line 367, in loads return cls(**kw).decode(s)

File "/usr/lib/python3.6/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end())

File "/usr/lib/python3.6/json/decoder.py", line 355, in raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 1093156512 (char 1093156511)

当我在那里寻找时,我得到:

eers in the fridge!"}, {"city_name": "Portland", "comments": "A cute space to rest your head in Portland. We just stayed for one night, briefly met Adam who was lovely! Appreciated the beers and coffe 

请您参考如下方法:

我在 Luminoso 发现了好人已经写了一个图书馆来解决这类问题。

显然,有时您可能需要处理来自其他代码的文本。其中文本经常通过几个不同的软件,每个都有自己的怪癖,可能在链中的某个地方有 Microsoft Office。

这是ftfy的地方来救援。

from ftfy import fix_text 
import json 
# text = some text source with a potential unicode problem 
fixed_text = fix_text(text) 
data = json.loads(fixed_text)