Python convert OrderedDict saved as string into an actual dict
Asked Answered
S

3

5

I have a Postgres db where OrderedDict has been saved as a string. I need to convert this string into json/dict so that it can be saved in a JSONField. How can I convert this string into dict?

String example -

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

I tried json.loads(string) but it gives a decoding error. Any solution apart from manually parsing the string?

Schramke answered 10/5, 2019 at 6:33 Comment(3)
eval(string) ?Seaborg
@Seaborg I generally try to avoid eval since it seems unsafe. But in this case I guess it should be okaySchramke
I would also avoid eval but using regex or split() it would need more work and it would not predict all cases.Seaborg
T
11

You can use eval for this purpose.

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)

The output will be

{'order_id': 'xxxxxx', 'tracking_id': 'xxxxxx', 
'bank_ref_no': 'xxxxx', 'order_status': 'Success'}
Threecolor answered 10/5, 2019 at 6:41 Comment(0)
I
3

I know you mentioned you want a solution without actual parsing, but the parsing option could be pretty simple too:

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)
Inobservance answered 10/5, 2019 at 6:42 Comment(0)
V
0

Another approach is to use Regex to extract the list and then use ast module.

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"(?<=OrderedDict\()(.*)\)$", s).group(1))))

Output:

OrderedDict([('order_id', 'xxxxxx'), ('tracking_id', 'xxxxxx'), ('bank_ref_no', 'xxxxx'), ('order_status', 'Success')])
Varsity answered 10/5, 2019 at 6:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.