how to remove 'escape slash' in json?

Viewed 4704

I need to remove escape sequence. How can I do it using python?

  • Current results
"conv": "\"XXXXX\"",
  • After shaping(I want to get this)
"conv": "XXXXX",
4 Answers

Use replace

conv = "\"XXXXX\""
conv = conv.replace("\"", "")

You can remove string using str.replace method.

'\"XXXXX\"'.replace("\"","") # returns 'XXXXX'

Here's how to use str.replace()

You can use json decoder

import json
x = {"conv": "\"XXXXX\""}
x['conv'] = json.loads(x['conv']) # sets conv to "XXXXX"

You need to double-up on the back-slashes, otherwise you will not end up with something that will parse as json because otherwise you are just replacing all " characters and leaving the backslash:

s = s.replace('\\"', '')
import json


d = {"conv": "\"XXXXX\""}
s = json.dumps(d)
print(s) # -> {"conv": "\"XXXXX\""}
s = s.replace('\\"', '')
print(s) # -> {"conv": "XXXXX"}
print(json.loads(s)) # -> {'conv': 'XXXXX'}
Related