Python – Unescape quotes from JSON string

I had a data dump that stored JSON data in escaped/serialized format. Here’s a sample:

escaped_json = '{\"payload\":{\"0\":{\"k1\":\"v1\", \"k2\":\"v2\", \"k3\":\"v3\"}, \"1\":{\"k4\":\"v5\", \"k6\":\"v4\", \"k5\":\"v6\"}}}'

I wanted to convert this into valid JSON that can be ready by any parser. I had an option to substitute ” with ” but then there might have been other chars in the string, escaped or serialized that would have caused trouble later on. So I found this useful way of unescaping the text:

json_string = escaped_json.decode('string_escape')

to return:

'{"payload":{"0":{"k1":"v1", "k2":"v2", "k3":"v3"}, "1":{"k4":"v5", "k6":"v4", "k5":"v6"}}}'

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s