【问题标题】:How to take a dictionary and send a JSON Response如何获取字典并发送 JSON 响应
【发布时间】:2013-06-13 18:14:43
【问题描述】:

我有以下功能,

def facebooktest(request):
    fb_value = ast.literal_eval(request.body)
    fb_foodies = Foodie.objects.filter(facebook_id__in = fb_value.values())
    for fb_foodie in fb_foodies:
        state = request.user.relationships.following().filter(username = fb_foodie.user.username).exists()
        userData = {
            'fbid': fb_foodie.facebook_id,
            'followState': int(state),
                }

基本上,我正在查看用户的哪些 Facebook 朋友在我的 django 应用程序上。如果是,则返回 followState。 followState 基本上返回 1 或 0。如果用户已经在我的 Django 应用程序上关注他们,则返回 1;如果他们没有在我的 Django 应用程序上关注他们的 Facebook 朋友,则返回 0。

我想向该用户返回一个 json 类型的字典,如下所示:

[{fbid:222222222222, followState: 0}, {fbid:111111111111, followState: 1}, {fbid:435433434534, followState:1}]

编辑

我有字典结构,但我只想像上面的结构一样返回它。

【问题讨论】:

    标签: python django json dictionary


    【解决方案1】:
    def facebooktest(request):
        fb_value = ast.literal_eval(request.body)
        fb_foodies = Foodie.objects.filter(facebook_id__in = fb_value.values())
        response = []
        for fb_foodie in fb_foodies:
            state = request.user.relationships.following().filter(username = fb_foodie.user.username).exists()
            userData = {
                'fbid': fb_foodie.facebook_id,
                'followState': int(state),
                    }
            response.append(userData)
        return json.dumps(response)
    

    【讨论】:

    • 这不是一个视图,因为它不返回 HttpResponse,但它返回具有您要求的结构的 JSON 字符串。
    • 谢谢,我们搞定了!
    【解决方案2】:

    django.forms.models 包中有一个函数:model_to_dict

    from django.forms.models import model_to_dict
    
    model_to_dict(your_model, fields=[], exclude=[])
    

    来自帮助:

    model_to_dict(instance, fields=None, exclude=None)
        Returns a dict containing the data in ``instance`` suitable for passing as
        a Form's ``initial`` keyword argument.
    
        ``fields`` is an optional list of field names. If provided, only the named
        fields will be included in the returned dict.
    
        ``exclude`` is an optional list of field names. If provided, the named
        fields will be excluded from the returned dict, even if they are listed in
        the ``fields`` argument.
    

    【讨论】:

    • 我编辑了我的问题,请看一下!我想我可能还不清楚:)
    • 我的回答确实无关紧要!
    【解决方案3】:

    我想你正在寻找这个:

    return HttpResponse(simplejson.dumps(response_dict), mimetype='application/json')
    

    “response_dict”将是您的字典。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-23
      • 2011-12-21
      • 2018-05-27
      • 2023-04-03
      相关资源
      最近更新 更多