Search code examples
pythonarraysstringdeserializationpickle

Deserializing array of arrays from a string


I need to deserialize an array of arrays from a string like '[["a", "b"], ["c", "d"]]'.

I tried using pickle, but I didn't really get how to use it.

How can I deserialize this string?


Solution

  • Use ast.literal_eval():

    import ast
    
    ast.literal_eval('[["a", "b"], ["c", "d"]]')
    

    This outputs:

    [['a', 'b'], ['c', 'd']]
    

    (As a side note, you should use ast.literal_eval() over eval() whenever possible, for security reasons. More information on this can be found here. eval() can be extremely dangerous, and you should only use it unless you're aware of its risks.)