django:控制json序列化 [英] django: control json serialization

查看:97
本文介绍了django:控制json序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法控制django中的json序列化?以下简单代码将返回json中的序列化对象:

  co = Collection.objects.all()
c = serializers。序列化('json',co)

json将类似于这样:

  [
{
pk:1,
model:picviewer.collection,
fields:{
urlName:architecture,
name:\\\Г\\\о\\\р\\\о\\\д \\\и \\\а \\\р\\\х\\\и\\\т\\\е\\\к\\\т\\\у\\\т\\\у\\\р\\\а,
sortOrder:0
}
},
{
pk:2,
model:picviewer.collection,
fields:{
urlName:nature ,
name:\\\П\\\р\\\и\\\р\\\о\\\д\\\а,
sortOrder:1
}
},
{
pk:3,
model:picviewer.collection,
fields:{
urlName:objects,
name:\\\О\\\б\\\ъ\\\е\\\к\\\т\\\ы \\\и \\\н\\\а\\\т\\\ю\\\р\\\м\\\о \\\р\\\т,
sortOrder:2
}
}
]

您可以看到它以一种可以重新创建整个模型的方式进行序列化,您是否希望在某个时候做到这一点 - 足够公平,但不太方便简单的JS ajax在我的情况下:我想要使流量最小化,使整个事情变得更清楚。



我所做的是创建一个将对象传递给一个.json模板和模板将会这样做来生成更好的json输出:

  [
{ %如果集合%}
{%在集合中的c%}
{id:{{c .id}},sortOrder:{{c.sortOrder}},name:{{c.name}},urlName:{{c.urlName}}}} {%if not forloop .last%},{%endif%}
{%endfor%}
{%endif%}
]

这样做会很好(?)更好:

  
{
id:1,
sortOrder:0,
name:Городиархитектура,
urlName
},
{
id:2,
sortOrder:1,
name:Природа,
urlName :nature
},
{
id:3,
sortOrder:2,
name:Объектыинатюрморт,
urlName:objects
}
]

,我很困惑,我的解决方案使用模板(处理的额外步骤和可能的性能影响),它将需要手动工作来维护,我应该更新m odel,例如。

我认为json生成应该是模型的一部分(如果我错了,纠正我),并使用本机python-json和django实现,但不能弄清楚如何使我不需要的位。



还有一件事 - 即使我将它限制在一组字段要序列化,它将保持ID始终在元素容器之外,而是将其作为其外的pk。

解决方案

这很简单。快速示例:

从django.http导入HttpResponse 
从django.utils导入simplejson

def simple_view(request):
response = {'string':test,
'number':42,
'array':[1,2,3],
'js_object':dict(foo =bar)}
return HttpResponse(simplejson.dumps(response),
mimetype =application / json)

此视图将返回相当于以下JSON:

 code> {string:test,
number:42,
array:[1,2,3],
js_object:{foo :bar}}

编辑:是的,Assaf Lavie是对的,你的模板可以无效JSON。


Is there a way to control json serialization in django? Simple code below will return serialized object in json:

co = Collection.objects.all()
c = serializers.serialize('json',co)

The json will look similar to this:

[
    {
        "pk": 1,
        "model": "picviewer.collection",
        "fields": {
            "urlName": "architecture",
            "name": "\u0413\u043e\u0440\u043e\u0434 \u0438 \u0430\u0440\u0445\u0438\u0442\u0435\u043a\u0442\u0443\u0440\u0430",
            "sortOrder": 0
        }
    },
    {
        "pk": 2,
        "model": "picviewer.collection",
        "fields": {
            "urlName": "nature",
            "name": "\u041f\u0440\u0438\u0440\u043e\u0434\u0430",
            "sortOrder": 1
        }
    },
    {
        "pk": 3,
        "model": "picviewer.collection",
        "fields": {
            "urlName": "objects",
            "name": "\u041e\u0431\u044a\u0435\u043a\u0442\u044b \u0438 \u043d\u0430\u0442\u044e\u0440\u043c\u043e\u0440\u0442",
            "sortOrder": 2
        }
    }
]

You can see it's serializing it in a way that you are able to re-create the whole model, shall you want to do this at some point - fair enough, but not very handy for simple JS ajax in my case: I want bring the traffic to minimum and make the whole thing little clearer.

What I did is I created a view that passes the object to a .json template and the template will do something like this to generate "nicer" json output:

[
{% if collections %}
    {% for c in collections %}
{"id": {{c.id}},"sortOrder": {{c.sortOrder}},"name": "{{c.name}}","urlName": "{{c.urlName}}"}{% if not forloop.last %},{% endif %}
    {% endfor %}
{% endif %}
]

This does work and the output is much (?) nicer:

[
    {
        "id": 1,
        "sortOrder": 0,
        "name": "Город и архитектура",
        "urlName": "architecture"
    },
    {
        "id": 2,
        "sortOrder": 1,
        "name": "Природа",
        "urlName": "nature"
    },
    {
        "id": 3,
        "sortOrder": 2,
        "name": "Объекты и натюрморт",
        "urlName": "objects"
    } 
]

However, I'm bothered by the fast that my solution uses templates (an extra step in processing and possible performance impact) and it will take manual work to maintain shall I update the model, for example.

I'm thinking json generating should be part of the model (correct me if I'm wrong) and done with either native python-json and django implementation but can't figure how to make it strip the bits that I don't want.

One more thing - even when I restrict it to a set of fields to serialize, it will keep the id always outside the element container and instead present it as "pk" outside of it.

解决方案

That's really easy. Quick example:

from django.http import HttpResponse
from django.utils import simplejson

def simple_view(request):
    response = {'string': "test",
                'number': 42,
                'array': [1, 2, 3],
                'js_object': dict(foo="bar")}
    return HttpResponse(simplejson.dumps(response),
                        mimetype="application/json")

This view will return the equivalent of the following JSON:

{"string": "test",
 "number": 42,
 "array": [1, 2, 3],
 "js_object": {foo: "bar"}}

EDIT: And yes, Assaf Lavie is right, your template can spew invalid JSON.

这篇关于django:控制json序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆