To convert an array of objects to a string, I can use str(arr)
.
Reversely, is there a built-in Python function to convert a string representation of an array of object to an array of objects?
In other words, how to convert "[{'key1': 'val1', 'key2': 'val2'}]"
back to an array of objects? I thought of doing it using split
but it wouldn't be clean like str()
.
// examples
arr = [{'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}, {'key1': 'val1', 'key2': 'val2'}]
arrStr = str(arr)
// "[{'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}, {'key1': 'val1', 'key2': 'val2'}]"
arr2 = [{'key1': 'val1', 'key2': 'val2'}]
arrStr2 = str(arr)
// "[{'key1': 'val1', 'key2': 'val2'}]"
I would get ValueError: malformed node or string: <ast.Name object at ...>
for the following.
str1 = '[{"a":null,"b":true}]'
arr = ast.literal_eval(str1)
However, this would work. If there is single quote in the keys or values, this method would not work.
str1 = '[{"a":null,"b":true}]'
arr = json.loads(str1.replace("'",'"'))
// [{'a': None, 'b': True}]
Does anyone know an easy method to convert a string representation of an array of objects to an array of objects?
I have seen How to convert string representation of list to a list? in case you want to mark it as duplicate and close.