首页 > 解决方案 > json.decoder.JSONDecodeError:从 txt 文件读取 json 时出现预期值错误

问题描述

我正在尝试使用 JSON 从 .txt 文件中读取一些数据,但出现以下错误。我尝试了各种方法,例如尝试修复错误,但没有任何内容。

json.decoder.JSONDecodeError: 
 Expecting value Error when reading json from txt file

除了修改代码,我还尝试将输入文件转换为 JSON 格式。

我的数据示例:

("TeamSoft is seeking an IT Support Specialist to join our client in Madison, WI.", {"entities":[ (1, 9, 'ORG'), (24, 45, 'JOB'), (68, 75, 'GPE'), (77, 79, 'GPE') ]}),

Python:

def readData(path):    
    lines = []
    inputfile=open(path, "r")
    for line in inputfile:
        line = json.loads(line)
        lines.append(line)
    return lines

我想把它放在一个列表中,这样我就可以从一个文件中训练我的 Spacy NER 模型。当我尝试将其作为文本阅读时,它引发了错误。Spacy 的一位联合创始人告诉我将其读取为 json。

标签: pythonjsonfile

解决方案


那不是有效的 JSON;它有很多问题。

JSON 没有元组类型,因此括号无效。您需要将它们全部设为数组。

此外,所有字符串都需要有双引号;并且您不能以尾随逗号结束数组或对象。

[
    "TeamSoft is seeking an IT Support Specialist to join our client in Madison, WI.",
     {"entities": [ [1, 9, "ORG"], [24, 45, "JOB"], [68, 75, :"GPE"], [77, 79, "GPE"] ]}
]

推荐阅读