Convert stringified list of dictionaries back to a list of dictionaries

前端 未结 3 359
时光取名叫无心
时光取名叫无心 2021-01-19 04:17

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

3条回答
  •  滥情空心
    2021-01-19 04:56

    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.

提交回复
热议问题