-1

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?

morfys
  • 2,195
  • 3
  • 28
  • 35

3 Answers3

4

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.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
3

JSON syntax is not Python syntax. JSON requires double quotes for its strings.

Arbazz Hussain
  • 1,622
  • 2
  • 15
  • 41
3

Because str() uses simple quotes as default, and JSON requires double quotes.

For more details about str(), see this

TheWildHealer
  • 1,546
  • 1
  • 15
  • 26