简体   繁体   English

使用Python simplejson返回预生成的json

[英]Using Python simplejson to return pregenerated json

I have a GeoDjango model object that I want't to serialize to json. 我有一个GeoDjango模型对象,我不想序列化为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. 问题是simplejson将a.area.geojson视为一个简单的字符串,即使它是美丽的预生成json。 This is easily fixed in the client by eval() 'ing the area-string, but I would like to do it proper. 这很容易通过eval()的区域字符串在客户端修复,但我想这样做。 Can I tell simplejson that a particular string is already json and should be used as-is (and not returned as a simple string)? 我可以告诉simplejson特定字符串已经是json并且应该按原样使用(并且不作为简单字符串返回)吗? Or is there another workaround? 或者还有另一种解决方法吗?

UPDATE Just to clarify, this is the json currently returned: 更新只是为了澄清,这是当前返回的json:

{
    "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. 挑战是让“area”成为json字典而不是简单的字符串。

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. 我认为干净的方法是扩展JSONEncoder,并创建一个检测给定对象是否已经是JSON的编码器。 if it is - it just returns it. 如果是 - 它只是返回它。 If its not, it uses the ordinary JSONEncoder to encode it. 如果不是,它使用普通的JSONEncoder对其进行编码。

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). 如果你有一个更简洁的方法来测试某些东西已经是JSON, 使用它(我的方式 - 寻找以'{'开头并以'}结尾的字符串是丑陋的)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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