【问题标题】:Serialize Dictionary with a string key and List[] value to JSON使用字符串键和 List[] 值将字典序列化为 JSON
【发布时间】:2011-02-07 01:10:24
【问题描述】:

如何将python字典序列化为JSON并传回javascript,其中包含一个字符串键,而值是一个列表(即[])

if request.is_ajax() and request.method == 'GET':

   groupSet = GroupSet.objects.get(id=int(request.GET["groupSetId"]))
   groups = groupSet.groups.all()

   group_items = [] #list
   groups_and_items = {} #dictionary

   for group in groups:
      group_items.extend([group_item for group_item in group.group_items.all()])
      #use group as Key name and group_items (LIST) as the value
      groups_and_items[group] = group_items 

    data = serializers.serialize("json", groups_and_items)

 return HttpResponse(data, mimetype="application/json")

结果:

[{"pk": 5, "model": "myApp.group", "fields": {"name": "\u6fb4\u9584", "group_items": [13]}}]

虽然 group_items 应该有很多 group_item 并且每个 group_item 应该有“名称”,而不仅仅是 Id,在这种情况下 Id 是 13。

我需要将组名以及 group_item 的 ID 和名称序列化为 JSON 并传回 javascript。

我是 Python 和 Django 的新手,如果您有更好的方法,请给我建议,不胜感激。太感谢了。 :)

【问题讨论】:

    标签: python ajax django json serialization


    【解决方案1】:

    您的“组”变量是 QuerySet 对象,而不是字典。您需要更明确地处理要返回的数据。

    import json
    groups_and_items = {}
    for group in groups:
        group_items = []
        for item in group.group_items.all():
            group_items.append( {'id': item.id, 'name': item.name} )
        # <OR> if you just want a list of the group_item names
        #group_items = group.group_items.all().values_list('name', flat=True) 
        groups_and_items[group.name] = group_items
    data = json.dumps(groups_and_items)
    

    您究竟希望您的数据是什么样子?以上应该给你data这样的:

    [{ 'groupA': [{'id': 1, 'name': 'item-1'}],
       'groupB': [{'id': 2, 'name': 'item-2'}, ...],
       'groupC': []
    }]
    

    或者,如果您只想要 group_item 名称列表:

    [{ 'groupA': ['item-1'],
       'groupB': ['item-2', ...],
       'groupC': []
    }]
    

    【讨论】:

      【解决方案2】:

      您应该使用 Python 的 json 模块来编码您的 JSON。

      另外,data = serializers 的缩进级别是多少?看起来它可能在 for 循环中?

      【讨论】:

      • sorry the line: data = serializers.serialize("json", groups_and_items) 应该和for循环同级,在这里粘贴代码有点困难。
      • 顺便说一句,json.dumps 和 serializers.serialize("json", something) 有什么区别?
      • 并且有可能一个键可以是其他类型,(例如自定义类型而不是字符串?)在这种情况下,我使用“组”作为键,它不是字符串,我打错了这篇文章的标题,对不起!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多