0

What is the difrence between:

  1. s1 = '["a"]'

  2. s2 = "['a']"

When I do json.loads, I get following error for s2 but s1 is fine:

>>> s1='["a2"]'
>>> s2="['a2']"
>>> json.loads(s1)
[u'a2']
>>> json.loads(s2)
 raise ValueError("No JSON object could be decoded")
 ValueError: No JSON object could be decoded
3
  • I'm not familiar with json, but does the method require specific input string format? Commented Mar 7, 2012 at 3:09
  • Please correct your code and exception information - the exception should be NameError, because you define s1 twice, but you define no s2. Please correct your code so it shows exactly what you saw. Commented Mar 7, 2012 at 3:11
  • 1
    @Ashish: Ok, I have corrected and formatted your question. Commented Mar 7, 2012 at 3:20

2 Answers 2

7

The problem is JSON uses double quotes (") for quoting values, not single ones (').

Which means the exception is thrown because of invalid JSON:

  • this is invalid JSON: ['a']
  • this is valid JSON: ["a"]

Also the correct example is below, different than yours:

>>> import json
>>> s1 = "['a']"
>>> s2 = '["a"]'
>>> json.loads(s1)
... some traceback removed ...
ValueError: No JSON object could be decoded
>>> json.loads(s2)
[u'a']

EDIT: I have updated the question with the correct output OP must have seen instead of what he/she posted (json.loads('["a2"]') was not throwing errors, json.loads("['a2']") was).

Sign up to request clarification or add additional context in comments.

Comments

3

json quotes are not interchangable like Python's are.

>>> import json
>>> print json.dumps("['a']")
"['a']"
>>> print json.dumps('["a"]')
"[\"a\"]"

In the second case the " need to be escaped

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.