1

I have a list of JSON objects as a string.

str = "[{'key1':'value1','key2':'value2'}, {'key1':'value1','key2':'value2','key3':'value3'}]"

Is there any way to store the string as a list into a variable?

arr = [{'key1':'value1','key2':'value2'}, {'key1':'value1','key2':'value2','key3':'value3'}]
4
  • 4
    Use json module. import json; arr = json.loads(str) Commented Mar 23, 2020 at 17:41
  • @hurlenko it's not valid json because of the single quotes. Commented Mar 23, 2020 at 17:47
  • Yep, missed that. Well in this case a simple arr = eval(str) will work just fine Commented Mar 23, 2020 at 17:49
  • @hurlenko thanks for the help, but eval would fail if any value is null. json.load() should do the trick if we make the JSON valid. Commented Mar 23, 2020 at 18:05

2 Answers 2

4

To not be bother by the json-quote problem, just use eval or ast.literal_eval

value = eval(value)

Because to have valid JSON, you may have double quotes, then pass it to json.loads, but this could be a problem if you have a double or single quote in the content

value = "[{'key1':'value1','key2':'value2'}, {'key1':'value1','key2':'value2','key3':'value3'}]"
value = json.loads(value.replace("'", '"'))
Sign up to request clarification or add additional context in comments.

1 Comment

This is likely to break if any of the string values contains '.
3

you could use ast.literal_eval:

from ast import literal_eval
my_str = "[{'key1':'value1','key2':'value2'}, {'key1':'value1','key2':'value2','key3':'value3'}]"
arr = literal_eval(my_str)
arr

output:

[{'key1': 'value1', 'key2': 'value2'},
 {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.