user2667066 user2667066 - 2 months ago 13
JSON Question

Do web2py json returns have extraneous whitespace, if so, how to remove

Just to check, the default JSON view which changes python objects to JSON seems to include whitespace between the variables, i.e.

"field": [[110468, "Octopus_vulgaris", "common octopus"...


rather than

"field":[[110468,"Octopus_vulgaris","common octopus"...


Is that right? If so, is there an easy way to output the JSON without the extra spaces, and is this for any reason (other than readability) a bad idea.

I'm trying to make some API calls return the fastest and most concise JSON representation, so any other tips gratefully accepted. For example, I see the view calls
from gluon.serializers import json
- does that get re-imported every time the view is used, or is python clever enough to use it once-only. I'm hoping the latter.

Answer

The generic.json view calls gluon.serializers.json, which ultimately calls json.dumps from the Python standard library. By default, json.dumps inserts spaces after separators. If you want no spaces, you will not be able to use the generic.json view as is. You can instead do:

import json
output = json.dumps(input, separators=(',', ':'))

If input includes some data that are not JSON serializable and you want to take advantage of the special data type conversions implemented in gluon.serializers.json (i.e., datetime objects and various web2py specific objects), you can do the following:

import json
from gluon.serializers import custom_json
output = json.dumps(input, separators=(',', ':'), default=custom_json)

Using the above, you can either edit the generic.json view, create your own custom JSON view, or simply return the JSON directly from the controller.

Also, no need to worry about re-importing modules in Python -- the interpreter only loads the module once.

Comments