【问题标题】:Replace single quotes (') with double quotes (") except apostrophe [duplicate]将单引号 (') 替换为双引号 ("),撇号除外 [重复]
【发布时间】:2019-07-07 01:25:06
【问题描述】:

我有一个包含无效 json 的数据集,请参阅下面的 sn-p:

{'id': 613, 'name': "new year's eve"}

我想替换除撇号之外的所有单引号,例如:new year's。所以上面的字符串应该会产生有效的 json,比如:

{"id": 613, "name": "new year's eve"}

我在 Python 中尝试了一个简单的字符串替换:string.replace("'", "\""),但这也改变了撇号,导致:

{"id": 613, "name": "new year"s eve"}

有没有办法用正则表达式来解决这个问题,比如全部替换 ' 除非用 " 封装?

【问题讨论】:

  • 我之前尝试过该解决方案,但在我的情况下它不起作用,因为它会导致无效的 json。

标签: python json regex replace


【解决方案1】:

您可以使用ast 模块

例如:

import ast

s = """{'id': 613, 'name': "new year's eve"}"""
d = ast.literal_eval(s)
print(d)

【讨论】:

  • 非常感谢!这正是我需要的。我是 Python 新手,还不知道这个函数。
  • 不客气 :)
【解决方案2】:

你可以试试

'(\w+)'\s*:

见a demo on regex101.com。


在Python:
import json, re

string = """{'id': 613, 'name': "new year's eve"}"""

rx = re.compile(r"""'(\w+)'\s*:""")
string = rx.sub(r'"\1":', string)
d = json.loads(string)
print(d)

这会产生

{'id': 613, 'name': "new year's eve"}

更好的是:这个字符串首先来自哪里?

【讨论】:

  • {'id': 613, 'name': "here is the content of my string 'foo': 'bar'"}
  • 感谢您的回复。这不起作用,因为它匹配引号之间的文本。我只想将 ' 更改为 " ,除非在以下作品中使用 ':year's。
  • @Cid:我很清楚它并不完美。
  • @user3190748:是的,确实如此。打印出来的d 已经是解析字典了。如果你想看到它已经改变,你可以打印出之前的字符串。
  • “更好的是:这个字符串最初是从哪里来的?”这个问题应该得到回答。一旦收到无效的 JSON,您就不必修复
猜你喜欢
  • 2018-11-19
  • 1970-01-01
  • 2018-11-18
  • 1970-01-01
  • 2017-12-29
  • 1970-01-01
  • 1970-01-01
  • 2021-08-12
  • 1970-01-01
相关资源
最近更新 更多