Tôi có một db postgres trong đó OrderedDict
đã được lưu dưới dạng chuỗi. Tôi cần chuyển đổi chuỗi này thành json/dict để nó có thể được lưu trong một jsonfield. Làm thế nào tôi có thể chuyển đổi chuỗi này thành dict?
Ví dụ về chuỗi -
OrderedDict[[['order_id', 'xxxxxx'], ['tracking_id', 'xxxxxx'], ['bank_ref_no', 'xxxxx'], ['order_status', 'Success']]]
Tôi đã thử json.loads[string]
nhưng nó gây ra lỗi giải mã. Bất kỳ giải pháp ngoài việc phân tích thủ công chuỗi?
Đã hỏi ngày 10 tháng 5 năm 2019 lúc 6:33May 10, 2019 at 6:33
3
Bạn có thể sử dụng
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]
0 cho mục đích này.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]
Đầu ra sẽ là
{'order_id': 'xxxxxx', 'tracking_id': 'xxxxxx',
'bank_ref_no': 'xxxxx', 'order_status': 'Success'}
Đã trả lời ngày 10 tháng 5 năm 2019 lúc 6:41May 10, 2019 at 6:41
Tôi biết bạn đã đề cập rằng bạn muốn một giải pháp mà không cần phân tích cú pháp thực tế, nhưng tùy chọn phân tích cú pháp cũng có thể khá đơn giản:
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]
Đã trả lời ngày 10 tháng 5 năm 2019 lúc 6:42May 10, 2019 at 6:42
Razdirazdirazdi
1.33014 Huy hiệu bạc18 Huy hiệu đồng14 silver badges18 bronze badges
Một cách tiếp cận khác là sử dụng Regex để trích xuất danh sách và sau đó sử dụng mô -đun
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]
1.Ex:
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"[?