Aaron
Aaron

Reputation: 199

Loading JSON object with special values as a string

I'm trying to create a string JSON object to load using the json module; however, I'm having some trouble since some of my values are the python True and False rather than unicode strings. For example, I want do the following:

>>> newDict = json.loads(u'{"firstKey": True, "secondKey": False}')
>>> newDict.get('firstKey') == True
True

but I'm getting:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/json/__init__.py", line 307, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python2.6/json/decoder.py", line 319, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib64/python2.6/json/decoder.py", line 336, in raw_decode
    obj, end = self._scanner.iterscan(s, **kw).next()
  File "/usr/lib64/python2.6/json/scanner.py", line 55, in iterscan
    rval, next_pos = action(m, context)
  File "/usr/lib64/python2.6/json/decoder.py", line 185, in JSONObject
    raise ValueError(errmsg("Expecting object", s, end))
ValueError: Expecting object: line 1 column 13 (char 13)

and of course if I change the True and False to "True" and "False", my condition is not met either as they are now strings and False would be returned.

Upvotes: 2

Views: 616

Answers (1)

wim
wim

Reputation: 363153

Can you use lowercase true and false?

>>> import json
>>> d = {'firstKey': True, 'secondKey': False}
>>> json.dumps(d)
'{"secondKey": false, "firstKey": true}'
>>> s = json.dumps(d)
>>> json.loads(s) == d
True

Upvotes: 4

Related Questions