Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python convert OrderedDict saved as string into an actual dict

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?

like image 232
Garvit Jain Avatar asked Dec 22 '22 23:12

Garvit Jain


1 Answers

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'}
like image 157
Devesh Kumar Singh Avatar answered May 24 '23 11:05

Devesh Kumar Singh