Using Python simplejson to return pregenerated json
django, geodjango, json, python, simplejson
Solution
EDITED after author's edit:
Can you do something like this:
lat = float(request.GET.get('lat'))
lng = float(request.GET.get('lng'))
a = Authority.objects.get(area__contains=Point(lng, lat))
if a:
json = simplejson.dumps({'name': a.name,
'area': "{replaceme}",
'id': a.id}),
return HttpResponse(json.replace('"{replaceme}"', a.area.geojson),
mimetype='application/json')
Problem
I have a GeoDjango model object that I want't to serialize to json. I do this in my view: ``` lat = float(request.GET.get('lat')) lng = float(request.GET.get('lng')) a = Authority.objects.get(area__contains=Point(lng, lat)) if a: return HttpResponse(simplejson.dumps({'name': a.name, 'area': a.area.geojson, 'id': a.id}), mimetype='application/json') ``` The problem is that `simplejson` considers the a.area.geojson as a simple string, even though it is beautiful pre-generated json. This is easily fixed in the client by `eval()`'ing the area-string, but I would like to do it proper. Can I tell `simplejson` that a particular string is already json and should be used as-is (and not returned as a simple string)? Or is there another workaround? UPDATE Just to clarify, this is the json currently returned: ``` { "id": 95, "name": "Roskilde", "area": "{ \"type\": \"MultiPolygon\", \"coordinates\": [ [ [ [ 12.078701, 55.649927 ], ... ] ] ] }" } ``` The challenge is to have "area" be a json dictionary instead of a simple string.