user4659009 user4659009 - 1 year ago 60
Python Question

Python: How do I convert a string inside a list to a json inside a list whilst retaining the double quotes

This is for python 3.x, I'm struggling to convert the following

['{"from": "USD", "to": "EUR"}']


to

[{"from": "USD", "to": "EUR"}]


I have tried using ast.literal_eval(s) but that returns my json in single quotes, I've been trying different combinations for well over an hour to no avail, any help is greatly appreciated!

Answer Source

Use json.loads and json.dumps. It will take care of it for you:

import json

a = ['{"from": "USD", "to": "EUR"}']
obj = json.loads(a[0])
print(obj, type(obj))
>> {'to': 'EUR', 'from': 'USD'} <class 'dict'>

print(json.dumps(obj), type(json.dumps(obj)))
>> {"to": "EUR", "from": "USD"} <class 'str'>