简体   繁体   中英

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!

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'>
>>> c=['{"from": "USD", "to": "EUR"}']
>>> c[0]
'{"from": "USD", "to": "EUR"}'
>>> eval( c[0])
{'to': 'EUR', 'from': 'USD'}
>>> p=eval(c[0])
>>> print p
{'to': 'EUR', 'from': 'USD'}
>>> type(p)
<type 'dict'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM