将嵌套字典列表反序列化为更简单的表单

时间:2010-12-02 19:49:31

标签: python django parsing serialization dictionary

我如何反序化:

[{'fields': {'active': 1,
             'image': 'http://img.rasset.ie/0003db75-150.jpg',
             'name': 'Bad Fellas',
             'position': 0,
             'url': 'http://www.rte.ie/tv/programmes/bad_fellas.html'},
  'model': 'rte_site.show',
  'pk': 1},
 {'fields': {'active': 1,
             'image': 'http://img.rasset.ie/0002c8d0-250.jpg',
             'name': 'Crimecall',
             'position': 0,
             'url': 'http://www.rte.ie/tv/crimecall/'},
  'model': 'rte_site.show',
  'pk': 2}]

形成:

{'1': {'pk': 1, "url": "http....", "image": 'http://....', 'name': 'Bad Fellas'}, '2': {...}}

?是否有可能以这种方式剥离它?


EDIT 我已经尝试了两种解决方案,我得到了:

string indices must be integers, not str

这是链接:http://ntt.vipserv.org/data/shows

和我的整个django函数代码:

def shows_json(request):
    objects = Show.objects.all()
    tmp = toJSON(objects)
    l = [{"pk": d["pk"], "url": d["fields"]["url"], "image": d["fields"]["image"], "name": d["fields"]["name"]} for d in tmp]
    json = dict(str((d["pk"]), d) for d in l)

    result = render_to_string('jsonlist.html', RequestContext(request, {
                'json': json,
            }))
    return HttpResponse(result)

def toJSON(obj):
   if isinstance(obj, QuerySet):
       return simplejson.dumps(obj, cls=DjangoJSONEncoder)
   if isinstance(obj, models.Model):
       set_obj = [obj]
       set_str = simplejson.dumps(simplejson.loads(serialize('json', set_obj)))
       str_obj = set_str[1:len(set_str)-2]
   return str_obj

from django.core.serializers import serialize
from django.utils.simplejson import dumps, loads, JSONEncoder
from django.db.models.query import QuerySet
from django.utils.functional import curry

class DjangoJSONEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, QuerySet):
            return loads(serialize('json', obj))
        return JSONEncoder.default(self,obj)
dumps = curry(dumps, cls=DjangoJSONEncoder)

2 个答案:

答案 0 :(得分:1)

>>> l = [{"pk": d["pk"], "url": d["fields"]["url"], "image": d["fields"]["image"], "name": d["fields"]["name"]} for d in l]
>>> new_data = dict((d["pk"], d) for d in l)
>>> new_data 
{1: {'url': 'http://www.rte.ie/tv/programmes/bad_fellas.html', 'pk': 1, 'image': 'http://img.rasset.ie/0003db75-150.jpg', 'name': 'Bad Fellas'}, 2: {'url': 'http://www.rte.ie/tv/crimecall/', 'pk': 2, 'image': 'http://img.rasset.ie/0002c8d0-250.jpg', 'name': 'Crimecall'}}

编辑:试试这个

def shows_json(request):
    objects = Show.objects.all()
    l = [{"pk": d["pk"], "url": d["fields"]["url"], "image": d["fields"]["image"], "name": d["fields"]["name"]} for d in objects]
    tmp = dict(str((d["pk"]), d) for d in l)
    json = toJSON(tmp)
    result = render_to_string('jsonlist.html', RequestContext(request, {
                'json': json,
            }))
    return HttpResponse(result)

答案 1 :(得分:0)

我认为你正在寻找这样的东西:

dict((x['pk'], x['fields']) for x in your_list)