使用Python simplejson返回预生成的json
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为最干净的方法是扩展 JSONEncoder,并创建一个编码器来检测给定对象是否已经是 JSON。如果是 - 它只会返回它。如果不是,则使用普通的 JSONEncoder 对其进行编码。
在您看来,您可以使用:
如果您有更清晰的方法来测试某些内容是否已经是 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.
and in your view, you use:
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: