I get a ValueError when loading a stringified list using str with json.loads. E.g.
l = ['a', 'b']
l_str = str(l)
l_loaded = json.loads(l_str)
However, this works:
x = '["a", "b"]'
x_loaded = json.loads(x)
Why is this?
I get a ValueError when loading a stringified list using str with json.loads. E.g.
l = ['a', 'b']
l_str = str(l)
l_loaded = json.loads(l_str)
However, this works:
x = '["a", "b"]'
x_loaded = json.loads(x)
Why is this?
Try printing out the value of l_str
. You'll see
['a', 'b']
not the
["a", "b"]
that you're comparing it to.
And even if this happened to work, it's not a good idea to muddle formats like this. What if someone came along and gave you the list [None, object(), open("/usr/bin/python3", "r")]
? That is definitely not going to be valid JSON when stringified.
JSON syntax is not Python syntax. JSON requires double quotes for its strings.
Because str() uses simple quotes as default, and JSON requires double quotes.
For more details about str(), see this