Reputation: 3225
Is there a best-practice for outputting Booleans in Python? I'm generating some JSON (via Django templates), and by default all the Boolean values are output with leading character in uppercase, contrary to the JSON standard (ie, "True" as opposed to "true").
Currently, I format each Boolean string using str.lower(), but is there a better way?
Upvotes: 6
Views: 24912
Reputation: 328760
Use the json module:
>>> import json
>>> json.dump(dict(value=True), sys.stdout)
{"value": true}
Upvotes: 2
Reputation: 13117
The better way would be to avoid generating JSON by hand, or via Django templates, and instead use a proper JSON library. In Python 2.6+ this is as simple as import json
. In older Pythons, you'll need to pip install simplejson
and import simplejson as json
.
It can be tough to generate proper JSON on your own—your experience with manually serializing bool
values is just the beginning. For another example, what about properly escaping strings with nested quotes?
Upvotes: 1
Reputation: 129914
Well, then serialise to JSON using json
, not some custom thingy.
import json
print json.dumps({'foo': True}) # => {"foo": true}
Upvotes: 10
Reputation: 95606
The way to do this is to not use templates. Use the json module, as so:
import json
def my_view(request):
# ...
json_d = dict(...)
return json.dumps(json_d)
My preferred way is to write a decorator, and return a dict.
def json_view(f):
def wrapped_f(*args, **kwargs):
return json.dumps(f(*args, **kwargs))
wrapped_f.original = f # for unit testing
return wrapped_f
@json_view
my_view(request):
# ...
return dict(...)
Upvotes: 7