使用Python simplejson返回预生成的json

发布于 2024-08-16 21:23:36 字数 930 浏览 5 评论 0原文

我有一个 GeoDjango 模型对象,我不想将其序列化为 json。我认为这样做是这样的:

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

问题是 simplejson 将 a.area.geojson 视为一个简单的字符串,即使它是漂亮的预先生成的 json。通过对区域字符串进行eval()处理,可以在客户端轻松修复此问题,但我想正确执行此操作。我可以告诉 simplejson 特定字符串已经是 json 并且应该按原样使用(而不是作为简单字符串返回)?或者还有其他解决方法吗?

更新 澄清一下,这是当前返回的 json:

{
    "id": 95,
    "name": "Roskilde",
    "area": "{ \"type\": \"MultiPolygon\", \"coordinates\": [ [ [ [ 12.078701, 55.649927 ], ... ] ] ] }"
}

挑战是让“area”成为 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜味拾荒者 2024-08-23 21:23:36

我认为最干净的方法是扩展 JSONEncoder,并创建一个编码器来检测给定对象是否已经是 JSON。如果是 - 它只会返回它。如果不是,则使用普通的 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)

在您看来,您可以使用:

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

如果您有更清晰的方法来测试某些内容是否已经是 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. 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).

风向决定发型 2024-08-23 21:23:36

作者编辑后编辑:

你能做这样的事情吗:

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

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')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文