Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace single quotes (') with double quotes (") except apostrophe [duplicate]

I have a dataset with invalid json, see snippet below:

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

I want to replace all the single quotes except apostrophes like in: new year's. So the string above should result in valid json like:

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

I have tried a simple string replace in Python: string.replace("'", "\""), but this also changes the apostrophe resulting in:

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

Is there a way to fix this with regex, like replace all ' except when encapsulated by "?

like image 760
user3190748 Avatar asked Sep 06 '25 22:09

user3190748


1 Answers

You can use the ast module

Ex:

import ast

s = """{'id': 613, 'name': "new year's eve"}"""
d = ast.literal_eval(s)
print(d)
like image 182
Rakesh Avatar answered Sep 08 '25 10:09

Rakesh