I know that to convert a dictionary to/from a string, I use json.loads
and json.dumps
. However, those methods fail when given a string representing
You may use ast.literal_eval:
>>> import ast
>>> my_str = "[{'topic': 'obama', 'interval': 'daily', 'type': 'test'}, {'topic': 'biden', 'interval': 'immediate', 'type': 'test'}]"
>>> ast.literal_eval(my_str)
[{'interval': 'daily', 'type': 'test', 'topic': 'obama'}, {'interval': 'immediate', 'type': 'test', 'topic': 'biden'}]
As per the ast.literal_eval document, it:
Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.