0

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'}]"
Jun
  • 2,942
  • 5
  • 28
  • 50
  • it is not even the same as the linked duplicated question. https://stackoverflow.com/questions/1894269/how-to-convert-string-representation-of-list-to-a-list – Jun May 02 '21 at 06:23

1 Answers1

-1
import json

array_of_objects = json.loads("[{'key1': 'val1', 'key2': 'val2'}]".replace("'",'"'))

Here's a speed comparison for the concerned parties:

import ast
import json

s = "[{'key1': 'val1', 'key2': 'val2'}]"

def kludge():
    json.loads(s.replace("'",'"'))

def fast():
    ast.literal_eval(s)
    
%timeit kludge()
%timeit fast()
>>> 2.02 µs ± 14.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>>> 10 µs ± 25.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Daniel Scott
  • 979
  • 7
  • 16