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'}]"

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Jun
  • 2,942
  • 5
  • 28
  • 50
  • 1
    Python printing a list would not produce `'[{"a":null,"b":true}]'`. That looks more like json serialized list from `[{'a': None, 'b': True}]` so you would use `json.loads`. *Don't* do the `str1.replace("'",'"')` thing because it could corrupt actual string values in the data. – wim May 04 '21 at 00:55
  • @wim I get this from an API so I have no control over the input. I agree that `str.replace` would corrupt the actual string values but ast wouldn't work here. Do you have any idea how to handle this? – Jun May 04 '21 at 01:03
  • 3
    If you're getting it from an API, it's probably JSON, so use `json.loads()` – Barmar May 04 '21 at 01:04
  • @Barmar thanks. It seems that json.loads() directly works. – Jun May 04 '21 at 01:12

0 Answers0