Python将保存为字符串的OrderedDict转换为实际的dict

Gar*_*ain 4 python json ordereddict

我有一个 Postgres db,其中OrderedDict已保存为字符串。我需要将此字符串转换为 json/dict,以便将其保存在 JSONField 中。如何将此字符串转换为dict?

字符串示例 -

OrderedDict([('order_id', 'xxxxxx'), ('tracking_id', 'xxxxxx'), ('bank_ref_no', 'xxxxx'), ('order_status', 'Success')])
Run Code Online (Sandbox Code Playgroud)

我试过了,json.loads(string)但它给出了解码错误。除了手动解析字符串之外还有其他解决方案吗?

Dev*_*ngh 7

您可以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)
Run Code Online (Sandbox Code Playgroud)

输出将是

{'order_id': 'xxxxxx', 'tracking_id': 'xxxxxx', 
'bank_ref_no': 'xxxxx', 'order_status': 'Success'}
Run Code Online (Sandbox Code Playgroud)