4

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

字符串示例 -

OrderedDict([('order_id', 'xxxxxx'), ('tracking_id', 'xxxxxx'), ('bank_ref_no', 'xxxxx'), ('order_status', 'Success')])

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

4

3 回答 3

8

您可以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'}
于 2019-05-10T06:41:49.867 回答
3

我知道您提到您想要一个没有实际解析的解决方案,但解析选项也可能非常简单:

import ast

a = "OrderedDict([('order_id', 'xxxxxx'), ('tracking_id', 'xxxxxx'), ('bank_ref_no', 'xxxxx'), ('order_status', 'Success')])"

# get the inner list representation
a = a.replace("OrderedDict(", '')
a = a[:-1]

# convert to a list of tuples
x = ast.literal_eval(a)

dict(x)
于 2019-05-10T06:42:03.050 回答
0

另一种方法是使用正则表达式提取列表,然后使用ast模块。

前任:

import re
import ast
from collections import OrderedDict

s = """OrderedDict([('order_id', 'xxxxxx'), ('tracking_id', 'xxxxxx'), ('bank_ref_no', 'xxxxx'), ('order_status', 'Success')])"""

print(OrderedDict(ast.literal_eval(re.search(r"(?<=OrderedDict\()(.*)\)$", s).group(1))))

输出:

OrderedDict([('order_id', 'xxxxxx'), ('tracking_id', 'xxxxxx'), ('bank_ref_no', 'xxxxx'), ('order_status', 'Success')])
于 2019-05-10T06:51:11.563 回答