0

I have the following structure as a list (originally returned as a result set from django ORM):

{'valuex': 65.92, 'day': datetime.date(2014, 10, 15), 'valuey': 74}{'valuex': 58.55, 'day': datetime.date(2014, 10, 16), 'valuey': 61}

And I'd like to transform it (and output it) as the following json:

{
'2014-10-15' : { 'valuex': 65.92, 'day': datetime.date(2014, 10, 15), 'valuey': 74 }, 
'2014-10-16' : { 'valuex': 58.55, 'day': datetime.date(2014, 10, 16), 'valuey': 61 }
}

I assumed that it would be something trivial like:

ret = {}
for r in results:
    ret[r.get('day')] = r

and then outputing to json could be done by Django (@render_to_json) But that really only returns the dates with no corresponding dictionary.

I'm new to Python and I'm lost here.

UPDATE:

I found out that the actual issue is that Django is not outputing my structure as json. the script above actually does create the structure I'm trying to achieve. but django fails to convert it to json. is it safe to do:

return HttpResponse(str(ret))

instead? Or is there some way to make it render to proper json (json.dumps has the same issue).

UPDATE2: Okay, json.dumps(ret) acutally did work for me, only needed to get rid of the datetime object as it's not json seralizeable.

  • Please don't "update" your question with a different one. If you have a new question ask it as a separate one. – dmg Feb 02 '15 at 08:02
  • I have updated the amswer below too >>> from django.http import JsonResponse >>> response = JsonResponse({'foo': 'bar'}) >>> response.content '{"foo": "bar"}' – Naveen Feb 02 '15 at 08:04
  • @dmg This is not a new question. It even says in the title 'outputting it as json', I didn't know what my specific problem was - building the structure or outputting it. Anyway the updates answer the question for anyone who ever stumbles on the same problem. – Yossi Ben Haim Feb 02 '15 at 17:55

3 Answers3

0
import datetime

results = [{'valuex': 65.92, 'day': datetime.date(2014, 10, 15), 'valuey': 74}, {'valuex': 58.55, 'day': datetime.date(2014, 10, 16), 'valuey': 61}]

ret = {}
for r in results:
    ret.update({str(r['day']): r})

print ret
{'2014-10-16': {'day': datetime.date(2014, 10, 16), 'valuey': 61, 'valuex': 58.55}, '2014-10-15': {'day': datetime.date(2014, 10, 15), 'valuey': 74, 'valuex': 65.92}}
Andrew
  • 3,711
  • 2
  • 20
  • 17
0

Solution #1

return HttpResponse(json.dumps({'result': 'done'}), content_type='application/json')

Solution #2

class JSONResponse(HttpResponse):

    """
    An HttpResponse that renders its content into JSON.
    """
def __init__(self, data, **kwargs):
    content = simplejson.dumps(data)
    kwargs['content_type'] = 'application/json'
    super(JSONResponse, self).__init__(content, **kwargs)

in view instead of HttpResponse write

data = {'success': True}
return JSONResponse(data)

Regarding datetime, you've to convert the datetime object to string using

my_datetime.strftime('<format>')

and use the same in your dict.

Tarun Behal
  • 908
  • 6
  • 11
0
import datetime

d1 = [{'valuex': 65.92, 'day': datetime.date(2014, 10, 15), 'valuey': 74},{'valuex': 58.55, 'day': datetime.date(2014, 10, 16), 'valuey': 61}]

for i in d1:
    d11 = dict([[str(i['day']),i]])
    print d11

{'2014-10-15': {'day': datetime.date(2014, 10, 15), 'valuey': 74, 'valuex': 65.92}}
{'2014-10-16': {'day': datetime.date(2014, 10, 16), 'valuey': 61, 'valuex': 58.55}}

OR

new_dict = {}
for i in di:
   new_dict[str(i['day'])] = i

Update:

Try this

>>> from django.http import JsonResponse
>>> response = JsonResponse({'foo': 'bar'})
>>> response.content
'{"foo": "bar"}'
Naveen
  • 230
  • 1
  • 3
  • 12
  • My Django doesn't have JsonResponse object (1.4 I believe, on google app engine). And in any case, since the @render_to_json annotation can't handle dictionary of dictionaries - I will be surprised if the code above would be any different. – Yossi Ben Haim Feb 02 '15 at 18:04