Python json boolean for string line

Is there any best practice for outputting boolean elements in Python? I generate some JSON (via Django templates), and by default all boolean values ​​are output with a leading character in uppercase, contrary to the JSON standard (ie "True", not "true").

I am currently formatting each logical line with str.lower (), but is there a better way?

+4
source share
4 answers

The way to do this is to not use patterns. Use the json module like this:

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(...) 
+4
source

Well then serialize in JSON using json and not some ordinary thing.

 import json print json.dumps({'foo': True}) # => {"foo": true} 
+6
source

Use json module :

 >>> import json >>> json.dump(dict(value=True), sys.stdout) {"value": true} 
+2
source

The best way would be to avoid creating JSON manually or using Django templates, and instead use the proper JSON library. In Python 2.6+, it is as simple as import json . In older Pythons, you need pip install simplejson and import simplejson as json .

It's hard to create your own JSON yourself - your experience with manually serializing bool values ​​is just the beginning. For another example, how to properly escape quoted strings?

+1
source

All Articles