-1

Why doesn't this work? I'm reading for simplejson JsonDecoder, true should be parsable and translated to True.

% python
>>> import simplejson as json
>>> print json.loads({"bool":true})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'true' is not defined
>>>
maverick
  • 2,902
  • 2
  • 19
  • 15

2 Answers2

7

The input to loads should be a string:

>>> json.loads('{"bool":true}')
{u'bool': True}
Vebjorn Ljosa
  • 17,438
  • 13
  • 70
  • 88
1

json.loads takes a string, which must be wrapped in quotes, like this:

o = json.loads(u'{"bool":true}')
print(o) # outputs  {u'bool': True}

Note that the u (which makes the string a character string in Python 2.x) is optional for this input and only becomes necessary if you're using non-ASCII characters such as ü, é, 编, or ℝ.

phihag
  • 278,196
  • 72
  • 453
  • 469
  • This doc is saying it converts from true to True. http://docs.python.org/library/json.html#json.JSONEncoder. Are you saying I have to alter my json because it is being parsed by Python? – maverick May 10 '12 at 23:15
  • This answer is wrong because the question asks about `loads`, which expects a string. – Mattie May 10 '12 at 23:36
  • @zigg This answer answers the original question, which was about dumps. maverick [changed it significantly](http://stackoverflow.com/posts/10543278/revisions). Updated. – phihag May 11 '12 at 07:20
  • @phihag Thanks for the clarification. I'll be sure to check edits next time. – Mattie May 11 '12 at 12:05