使用字符串键序列化Dictionary,将List []值序列化为JSON

时间:2022-10-26 16:23:22

How can I serialize a python Dictionary to JSON and pass back to javascript, which contains a string key, while the value is a List (i.e. [])

如何将python Dictionary序列化为JSON并传回包含字符串键的javascript,而值为List(即[])

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")

the result:

结果:

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

while the group_items should have many group_item and each group_item should have "name", rather than only the Id, in this case the Id is 13.

虽然group_items应该有很多group_item,每个group_item应该有“name”,而不是只有Id,在这种情况下Id是13。

I need to serialize the group name, as well as the group_item's Id and name as JSON and pass back to javascript.

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

I am new to Python and Django, please advice me if you have a better way to do this, appreciate. Thank you so much. :)

我是Python和Django的新手,如果你有更好的方法,请告诉我,欣赏。非常感谢。 :)

2 个解决方案

#1


1  

Your 'groups' variable is a QuerySet object, not a dict. You will want to be more explicit with the data that you want to return.

你的'groups'变量是一个QuerySet对象,而不是一个dict。您希望对要返回的数据更加明确。

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)

What exactly did you want you want your data to look like? The above should give you data like this :

您希望您希望数据看起来是什么样的?上面应该给你这样的数据:

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

Or this if you just want the list of group_item names:

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

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

#2


0  

You should use Python's json module to encode your JSON.

您应该使用Python的json模块对JSON进行编码。

Also, what indentation level do you have data = serializers at? It looks like it could be inside the for loop?

另外,你有什么缩进级别data = serializers?看起来它可能在for循环中?

#1


1  

Your 'groups' variable is a QuerySet object, not a dict. You will want to be more explicit with the data that you want to return.

你的'groups'变量是一个QuerySet对象,而不是一个dict。您希望对要返回的数据更加明确。

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)

What exactly did you want you want your data to look like? The above should give you data like this :

您希望您希望数据看起来是什么样的?上面应该给你这样的数据:

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

Or this if you just want the list of group_item names:

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

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

#2


0  

You should use Python's json module to encode your JSON.

您应该使用Python的json模块对JSON进行编码。

Also, what indentation level do you have data = serializers at? It looks like it could be inside the for loop?

另外,你有什么缩进级别data = serializers?看起来它可能在for循环中?