python json boolean to lowercase string

18,407

Solution 1

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(...)

Solution 2

Well, then serialise to JSON using json, not some custom thingy.

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

Solution 3

Use the json module:

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

Solution 4

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?

Share:
18,407

Related videos on Youtube

btk
Author by

btk

Updated on June 05, 2022

Comments

  • btk
    btk about 2 years

    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?

  • btk
    btk almost 13 years
    Thanks! For now I'm using {{variable_name|lower}}, but when I hit that wall (strings with quotes in them etc), I will refactor to use the json module.
  • Armando Pérez Marqués
    Armando Pérez Marqués almost 13 years
    Django ships with a version of the simplejson module, and if json module is available, then it it's used transparently. Just import it and you get with the best available option: from django.utils import simplejson or from django.utils import simplejson as json

Related