也许这个问题有点傻,但实际上我不知道如何解决它。我有一个json文件格式错误。它在第一个{之前有一个b‘,而且它使用单引号而不是双引号,而双引号不是json的公认格式。
我知道我必须用双引号代替单引号。我会用这样的方法:
json = file.decode('utf8').replace("'", '"')
但问题是,如果我无法打开文件中的引号,如何替换它呢?
import json
f = open("data/qa_Automotive.json",'r')
file = json.load(f)
打开文件会给我一个错误,因为它有单引号而不是双引号:
JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
如果我不能打开json文件中的引号,因为它的格式是错误的,我应该如何修改它呢?(这是json文件btw:https://jmcauley.ucsd.edu/data/amazon/qa/qa_Appliances.json.gz)
发布于 2021-01-10 02:33:08
该文件不是JSON (文件名不正确),而是由有效的Python文本组成。没有理由尝试将其转换为JSON。不要这样做;相反,只需要告诉Python按原样解析它。
#!/usr/bin/env python3
import ast, json
results = [ ast.literal_eval(line) for line in open('qa_Appliances.json') ]
print(json.dumps(results))
...properly为您提供了一个名为results
的列表,其中包含您的所有行,并且(为了演示目的)将其作为JSON转储到stdout。
发布于 2021-01-10 01:16:24
该文件存在多个问题:
的混合
第一个问题很容易解决,你可以单独加载每一行,第二个问题是骗子。
我试图(就像您所做的那样)简单地用"
替换"
。但这还不够,因为文本中有'
(比如“you‘s”),这里有一个单引号。如果您替换了所有的'
,那么它将被转换为一个"
并中断您的字符串。
您将得到类似于"message": "you"re"
的无效信息。
因为这个文件有很多问题,所以我建议使用一些脏的东西: python函数。
eval
简单地播放一个字符串,就好像它是一个命令一样。
>>> eval("4 + 2")
6
因为json格式和Python本机dict
类型非常接近(减去一些差别,比如Python True/False
和json使用true/false
)。Python使用None
,json使用null
,可能还有其他我忘记的),具有卷括号和平方括号的结构是相同的。但是在这里,由于Python既支持单引号,又支持双引号,所以"eval“可以帮助您。
使用文件中的一行:
>>> import json
>>>
>>> data = "{'questionType': 'yes/no', 'asin': 'B0002Z1GG0', 'answerTime': 'Dec 10, 2013', 'unixTime': 1386662400, 'question': 'would this work on my hotpoint model ctx14ayxkrwh serial hr749157 refrigerator do the drawers slide into slots ?', 'answerType': '?', 'answer': 'the drawers do fit into the slots.'}"
>>> parsed = eval(data)
>>> print(parsed)
{'questionType': 'yes/no', 'asin': 'B0002Z1GG0', 'answerTime': 'Dec 10, 2013', 'unixTime': 1386662400, 'question': 'would this work on my hotpoint model ctx14ayxkrwh serial hr749157 refrigerator do the drawers slide into slots ?', 'answerType': '?', 'answer': 'the drawers do fit into the slots.'}
>>> type(parsed)
<class 'dict'>
>>> print(json.dumps(parsed, indent=2))
{
"questionType": "yes/no",
"asin": "B0002Z1GG0",
"answerTime": "Dec 10, 2013",
"unixTime": 1386662400,
"question": "would this work on my hotpoint model ctx14ayxkrwh serial hr749157 refrigerator do the drawers slide into slots ?",
"answerType": "?",
"answer": "the drawers do fit into the slots."
}
我可以在整个文件中做到这一点:
>>> data = open("<path to file>").readlines()
>>> parsed = [ eval(line) for line in data ]
>>>
>>> len(parsed)
9011
>>> parsed[0]
{'questionType': 'yes/no', 'asin': 'B00004U9JP', 'answerTime': 'Jun 27, 2014', 'unixTime': 1403852400, 'question': 'I have a 9 year old Badger 1 that needs replacing, will this Badger 1 install just like the original one?', 'answerType': '?', 'answer': 'I replaced my old one with this without a hitch.'}
>>> parsed[0]['questionType']
'yes/no'
--您不应该对无卫生状态的数据使用eval
,因为它可以用来破坏您的系统,但是如果您在受控的环境中使用它,您就会使用它。
https://stackoverflow.com/questions/65649170
复制相似问题