【问题标题】:How to deal with single quotes in json format in Python?Python中如何处理json格式的单引号?
【发布时间】: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']]}
  1. 我试过了:

    df = pd.read_json('test.json',lines=True)
    

    这不起作用,因为我这里的 json 有单引号,这不是标准的 json 格式。

  2. 所以我也尝试了简单的shell脚本将所有单引号转换为双引号:

    cat test.json|sed "s/'/\"/g"
    

    这也不起作用,因为 json 包含评论文本,其中包含诸如 "It's the only real" 之类的东西;所以我们不能粗鲁地将所有单引号都转换成双引号。

  3. 然后我试着想用保留单引号直接转换怎么样:

    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。或者甚至只是创建这个。网址是什么?你是怎么下载的?

标签: python json pandas


【解决方案1】:

此问题不应在其标题或标记中的任何位置使用“JSON”,因为此数据不是 JSON

也就是说,ast.literal_eval() 工作正常,如果您转义换行文字。

s='''{'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']]}'''

import ast
ast.literal_eval(s.replace('\n', '\\n'))

【讨论】:

  • 谢谢!如果不是 JSON,那么它是什么?类似于 JSON?这是我从网上下载的数据。
  • 我认为这太迂腐了。这是 json 的轻微变化,其他人可能会遇到它并不是不切实际的,当他们搜索可能的答案时,他们会非常明智地搜索 json。事实上,它的 json 格式有些错误并不会使 json 不适用于标题或标签 - 这些反映的是人类语言,而不是编程语言。
猜你喜欢
  • 1970-01-01
  • 2011-11-16
  • 2021-01-08
  • 2016-11-14
  • 1970-01-01
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多