简体   繁体   中英

Using Python simplejson to return pregenerated json

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.

I think the clean way to do this is by extending JSONEncoder, and creating an encoder that detects if the given object is already JSON. if it is - it just returns it. If its not, it uses the ordinary JSONEncoder to encode it.

class SkipJSONEncoder(simplejson.JSONEncoder):
     def default(self, obj):
         if isinstance(obj, str) and (obj[0]=='{') and (obj[-1]=='}'): 
             return obj
         return simplejson.JSONEncoder.default(self, obj)

and in your view, you use:

simplejson.dumps(..., cls=SkipJSONEncoder)

If you have a cleaner way to test that something is already JSON, please use it (my way - looking for strings that start in '{' and end in '}' is ugly).

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM