我有一个 Postgres 数据库,其中 OrderedDict 已保存为字符串。我需要将此字符串转换为 json/dict,以便将其保存在 JSONField 中。如何将此字符串转换为字典?
字符串示例 -
OrderedDict([('order_id', 'xxxxxx'), ('tracking_id', 'xxxxxx'), ('bank_ref_no', 'xxxxx'), ('order_status', 'Success')])
我尝试了 json.loads(string) 但它给出了解码错误。除了手动解析字符串之外还有什么解决方案吗?
请您参考如下方法:
您可以为此目的使用eval。
from collections import OrderedDict
import json
x = "OrderedDict([('order_id', 'xxxxxx'), ('tracking_id', 'xxxxxx'), ('bank_ref_no', 'xxxxx'), ('order_status', 'Success')])"
#run string through eval and convert to dict
dct = dict(eval(x))
print(dct)
输出将是
{'order_id': 'xxxxxx', 'tracking_id': 'xxxxxx',
'bank_ref_no': 'xxxxx', 'order_status': 'Success'}
