Deserialize list of nested dictionaries to a simpler form
How I can deserialize this :
[{'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',
开发者_StackOverflow社区'pk': 2}]
to form :
{'1': {'pk': 1, "url": "http....", "image": 'http://....', 'name': 'Bad Fellas'}, '2': {...}}
? Is it even possible to strip it this way ?
EDIT I've tried two solutions and I'm getting :
string indices must be integers, not str
here's the link : http://ntt.vipserv.org/data/shows
and my whole code of django function:
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)
>>> 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'}}
Edit: try this
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)
I think you are looking for something like this:
dict((x['pk'], x['fields']) for x in your_list)
精彩评论