首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >向json响应添加根元素(django-rest-framework)

向json响应添加根元素(django-rest-framework)
EN

Stack Overflow用户
提问于 2013-02-12 11:15:39
回答 1查看 8.8K关注 0票数 21

我正在尝试确定使用django和django-rest-framework向所有json响应添加根元素的最佳方式。

我认为添加自定义渲染器是实现我想要实现的目标的最好方法,这就是我到目前为止想出的方法:

代码语言:javascript
复制
from rest_framework.renderers import JSONRenderer

class CustomJSONRenderer(JSONRenderer):
#override the render method
def render(self, data, accepted_media_type=None, renderer_context=None):
    #call super, as we really just want to mess with the data returned
    json_str = super(CustomJSONRenderer, self).render(data, accepted_media_type, renderer_context)
    root_element = 'contact'

    #wrap the json string in the desired root element
    ret = '{%s: %s}' % (root_element, json_str) 

    return ret

现在棘手的部分是基于调用render()的视图动态设置root_element

任何指示/建议都将非常感谢,

干杯

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14824807

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档