views:

132

answers:

2

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. [])

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.

I need to serialize the group name, as well as the group_item's Id and name as JSON and pass back to 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. :)

A: 

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

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

Justin Ethier
sorry the line:data = serializers.serialize("json", groups_and_items)should be same level as the for-loop, a bit hard to paste the code here.
Patrick
btw, what's the different between:json.dumps AND serializers.serialize("json", something)?
Patrick
And is that possible a Key can be other type, (e.g. a custom type rather than string? )in this case, I am using the "group" as the key, which is not a string, I mistype the title of this post, sorry for that!
Patrick
+1  A: 

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.

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:

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