Reputation: 420
Please advise a general regex pattern to replace below string to be able to parse with json.loads(string)
string
=
"""
[{'en': 'The chosen word is incorrect. Please make sure you don't use the "Other" word too often. Everything where you can buy things should be under the "Mall"', 'jp': "Bahasa yang dipilih salah, Pastikan anda tidak menggunakan Bahasa 'Lainnya'/'Other' terlalu sering. Semua hal dimana anda bisa membeli sesuatu harusnya menggunakan bahasa 'Mall'"}]
After i replace all the single quote with double quote. I am not able to find a general pattern to replace all internal double quote with single quote. """
Upvotes: 0
Views: 195
Reputation: 490
I added a\
to don\'t
to make :
d = {'en': 'The chosen word is incorrect. Please make sure you don\'t use the "Other" word too often. Everything where you can buy things should be under the "Mall"', 'jp': "Bahasa yang dipilih salah, Pastikan anda tidak menggunakan Bahasa 'Lainnya'/'Other' terlalu sering. Semua hal dimana anda bisa membeli sesuatu harusnya menggunakan bahasa 'Mall'"}
I used replace on each value item to get rid of all double quotes and turn them to single (otherwise the output will have \
behind each "
:
for k,v in d.items(): d[k] = v.replace("\"","'")
Then I used json.dumps(d) to get it into json format:
{"en": "The chosen word is incorrect. Please make sure you don't use the 'Other' word too often. Everything where you can buy things should be under the 'Mall'", "jp": "Bahasa yang dipilih salah, Pastikan anda tidak menggunakan Bahasa 'Lainnya'/'Other' terlalu sering. Semua hal dimana anda bisa membeli sesuatu harusnya menggunakan bahasa 'Mall'"}
EDIT :
import re pattern = "\"" repl = "'" s = """[{'en': 'The chosen word is incorrect. Please make sure you don't use the "Other" word too often. Everything where you can buy things should be under the "Mall"', 'jp': "Bahasa yang dipilih salah, Pastikan anda tidak menggunakan Bahasa 'Lainnya'/'Other' terlalu sering. Semua hal dimana anda bisa membeli sesuatu harusnya menggunakan bahasa 'Mall'"}]""" res = re.sub(pattern, repl, s) print(res)
Gives
[{'en': 'The chosen word is incorrect. Please make sure you don't use the 'Other' word too often. Everything where you can buy things should be under the 'Mall'', 'jp': 'Bahasa yang dipilih salah, Pastikan anda tidak menggunakan Bahasa 'Lainnya'/'Other' terlalu sering. Semua hal dimana anda bisa membeli sesuatu harusnya menggunakan bahasa 'Mall''}]
Upvotes: 1