Skip to content

Instantly share code, notes, and snippets.

@limeyd
Created October 16, 2013 03:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save limeyd/7002431 to your computer and use it in GitHub Desktop.
Save limeyd/7002431 to your computer and use it in GitHub Desktop.
py: tastypie-pretty-json-serializer
class PrettyJSONSerializer(Serializer):
json_indent = 2
def to_json(self, data, options=None):
options = options or {}
data = self.to_simple(data, options)
return simplejson.dumps(data, cls=json.DjangoJSONEncoder,
sort_keys=True, ensure_ascii=False, indent=self.json_indent)
@qn7o
Copy link

qn7o commented Sep 4, 2014

Update for Django 1.5+ (see release notes)

Django 1.5 deprecates django.utils.simplejson in favor of Python 2.6’s built-in json module.

class PrettyJSONSerializer(Serializer):
    json_indent = 4

    def to_json(self, data, options=None):
        options = options or {}
        data = self.to_simple(data, options)
        return json.dumps(data, sort_keys=True, ensure_ascii=False, indent=self.json_indent)

Then you just have to wire it to the resource:

class SomeResource(ModelResource):
    class Meta:
        queryset = SomeModel.objects.all()
        serializer = PrettyJSONSerializer()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment