Reputation: 83
I would like to replace this double quotes in string: Need to convert this string to valid JSON
data = '[{"Attribute":"Assembled Product Length","Keywords":"6.49"","AttributeComments":"Value Found","OtherComment":""},{"Attribute":"Assembled Product Width","Keywords":"2.75"","AttributeComments":"Value Found","OtherComment":""},{"Attribute":"Assembled Product Height","Keywords":"8.46"","AttributeComments":"Value Found","OtherComment":""},{"Attribute":"Diameter","Keywords":"","AttributeComments":"No Value Found","OtherComment":""}]'
Expected output:
data = '[{"Attribute":"Assembled Product Length","Keywords":"6.49","AttributeComments":"Value Found","OtherComment":""},{"Attribute":"Assembled Product Width","Keywords":"2.75","AttributeComments":"Value Found","OtherComment":""},{"Attribute":"Assembled Product Height","Keywords":"8.46","AttributeComments":"Value Found","OtherComment":""},{"Attribute":"Diameter","Keywords":"","AttributeComments":"No Value Found","OtherComment":""}]'
I had tried using python replace function:-
data = data.replace('""', '"')
But it didn't worked.
Upvotes: 0
Views: 69
Reputation: 2110
Replace "" with "
import re
data = '[{"Attribute":"Assembled Product Length","Keywords":"6.49"",...}]'
data = re.sub(':""', ":''", data)
data = data.replace('""','"')
data = data.replace("''",'""')
print(data)
Output:
[{"Attribute":"Assembled Product Length","Keywords":"6.49","AttributeComments":"Value Found","OtherComment":""},{"Attribute":"Assembled Product Width","Keywords":"2.75","AttributeComments":"Value Found","OtherComment":""},{"Attribute":"Assembled Product Height","Keywords":"8.46","AttributeComments":"Value Found","OtherComment":""},{"Attribute":"Diameter","Keywords":"","AttributeComments":"No Value Found","OtherComment":""}]
Upvotes: 3
Reputation: 382
There are two methods you can use:
Python has a built-in function str.replace(old, new)
So, you can directly replace it use: data.replace('""','"')
Regex (Regular Expression)
import re
data = re.sub('""+', '"', data)
That code means if quotes continuous appears twice, it will auto convert them to a single quote.
Upvotes: 2
Reputation: 68
How about:
data.replace('"",'"')
It replaces double quotes with a single one.
Upvotes: 2