【问题标题】:How to get rid of the nested double quote in 'name' subfield?如何摆脱“名称”子字段中的嵌套双引号?
【发布时间】:2019-07-02 23:19:37
【问题描述】:

我正在尝试使用 Python json 包将以下字符串读入字典

但是,在子字段“名称”之一下有一个带有嵌套双引号的描述。我的 json 无法以这种方式读取字符串

import json 

string1 = 
'{"id":17033,"project_id":17033,"state":"active","state_changed_at":1488054590,"name":"a.k.a.:\xa0"The Sunshine Makers""'

json.loads(string1)

引发了一个错误

JSONDecodeError: Expecting ',' delimiter: line 1 column 96 (char 95)

我知道这个错误的原因是由于 "The Sunshine Makers" 周围的嵌套双引号

如何去掉这个双引号?

更多导致错误的字符串示例

string2 = '{"id":960066,"project_id":960066,"state":"active","state_changed_at":1502049940,"name":"New J. Lye Album - Behind The Lyes","blurb":"I am working on my new project titled "Behind The Lyes" which is coming out fall of 2017."'

#The problem with this string comes from the nested double quote around the pharse "Behind The Lyes inside" the 'blurb' subfield 

【问题讨论】:

  • 您的字符串也缺少结束 }。确保问题得到解决。
  • 如果您希望保留引用,您可以通过将json.dumps()json.loads() 嵌套来解决此问题:print(json.loads(json.dumps(string1)))
  • string1 来自哪里?这是您在代码中创建的东西,还是从网站或数据库中获取的东西?
  • 另外,您的错误中的line 1, column 96 (char 95)\xa0
  • 垃圾进,垃圾出。修复输入,而不是试图找出如何解决脚本中的错误。

标签: python json regex double-quotes


【解决方案1】:

请注意,您的字符串存在多个问题,使其无效JSON

您看到的错误是\xa0(一个不间断的空格)。这需要在"" 问题成为问题之前解决。

您的字符串缺少结束 }

也就是说,对于您首先引用的字符串,解决问题的一种方法是使用.replace()

string1 = '{"id":17033,"project_id":17033,"state":"active","state_changed_at":1488054590,"name":"a.k.a.:\xa0"The Sunshine Makers""'.replace('\xa0"', "'").replace('""', "'\"") + '}'

例如,以下处理您的两个示例字符串中的双引号和其他问题:

import json 

fixes = [('\xa0', ' '),('"',"'"),("{'",'{"'),("','", '","'),(",'", ',"'),("':'", '":"'),("':", '":'),("''", '\'\"'), ("'}",'"}')]

print(fixes)
string1 = '{"id":17033,"project_id":17033,"state":"active","state_changed_at":1488054590,"name":"a.k.a.:\xa0"The Sunshine Makers""'
string2 = '{"id":960066,"project_id":960066,"state":"active","state_changed_at":1502049940,"name":"New J. Lye Album - Behind The Lyes","blurb":"I am working on my new project titled "Behind The Lyes" which is coming out fall of 2017."'
strings = [string1, string2]

for string in strings:
    print(string)
    string = string + '}'
    for fix in fixes:
        string = string.replace(*fix)
    print(string)
    print(json.loads(string)['name'])

如果您可以使用从中检索这些字符串的代码或文件来填写您的问题,将会很有帮助。这样就可以给出更全面的答案。

【讨论】:

  • 感谢您的评论。我之前尝试过替换,但它太复杂了,因为我必须解决每一个独特的模式(我有 100000 多行独特的条目,上面只是 2 个示例)。有没有更简单的方法来做到这一点?
  • 更简单的方法是修复创建数据框的解析器。如果像您描述的那样,您的数据将太随机了。
猜你喜欢
  • 2012-10-28
  • 2018-03-30
  • 1970-01-01
  • 2015-12-06
  • 2014-10-19
  • 1970-01-01
  • 1970-01-01
  • 2019-08-28
  • 1970-01-01
相关资源
最近更新 更多