【发布时间】:2017-11-12 01:28:11
【问题描述】:
我想将 json 格式转换为 pandas df。 json示例如下:
{'asin': '0615208479', 'description': "By now we all know the benefits of exercise for the body. It's the only real fountain of youth! The same is true for the brain. Take your brain to the gym several times a week and you can improve, regain and prevent memory loss. Discover the world of brain fitness through BrainAerboics.\nThe program was designed by a medical team and is backed with mounting research proving it works. It is believed to be the only one that combines the three crucial elements required for optimal brain fitness.", 'title': 'Brain Fitness Exercises Software', 'imUrl': 'http://ecx.images-amazon.com/images/I/41kbZB047NL._SY300_.jpg', 'salesRank': {'Health & Personal Care': 1346973}, 'categories': [['Health & Personal Care', 'Personal Care']]}
-
我试过了:
df = pd.read_json('test.json',lines=True)这不起作用,因为我这里的 json 有单引号,这不是标准的 json 格式。
-
所以我也尝试了简单的shell脚本将所有单引号转换为双引号:
cat test.json|sed "s/'/\"/g"这也不起作用,因为 json 包含评论文本,其中包含诸如
"It's the only real"之类的东西;所以我们不能粗鲁地将所有单引号都转换成双引号。 -
然后我试着想用保留单引号直接转换怎么样:
with open ('test.json') as f: s = f.read() print(ast.literal_eval(s))
但我得到了错误:
SyntaxError: invalid syntax
'categories': [['Health & Personal Care', 'Personal Care']]
【问题讨论】:
-
那不是有效的 json。
-
我知道。因为它不是双引号?那该怎么办呢?
-
首先创建实际的 JSON。
-
刚刚解决了以下问题:
ast.literal_eval(s.strip().replace('\n','\\n'))但您应该真的修复此问题的根源。制作这个文件并将其称为 JSON 的人非常糟糕。与其寻找解决办法,不如解决问题的根源 -
很难相信亚马逊会创建非 JSON 并将其称为 JSON。或者甚至只是创建这个。网址是什么?你是怎么下载的?