2

I'm working with django + piston and so far created a few urls that are returning my django models in JSON quite well. I didn't even have to specify an emitter, the JSON serialization is done automagically.

Now I need to return a JSON serialized object that does not extend Django Model class. If I return its value, piston returns the __ str __ value, even if I add the JSON emitter nothing happens. I don't want to add the JSON serialization in the __ str __ method since it wouldn't be correct. What's the correct approach for this?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Mariano
  • 91
  • 1
  • 1
  • 3

1 Answers1

1

You can use python's json package to do this.

Snippet:

>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'

If you're looking to create this in the context of django view, you'll want to make sure you're sending back the right content type. That is,

from django.http import HttpResponse
return HttpResponse(your_json_string, mimetype='application/json')

Note that this doesn't necessarily work for all types in general. It's usually a good idea to construct a dict containing exactly what you want to return, then serialize it.

almostflan
  • 640
  • 4
  • 15