7

I am trying to create a jSON object with sample output such as

{
    "pickups": [
        {
            "id": " ",
            "name": " ",
            "number": " ",
            "time": " ",
            "status": " "
        },
        {
            "id": " ",
            "name": " ",
            "time": " ",
            "number": " ",
            "status": " "
        }
    ]
}

I am getting a sample response like

  {'status': '1', 'time': datetime.date(2013, 2, 27), 'number': 4L, 'name': u'Dr  John', 'id': 83L}{'status': '1', 'time': datetime.date(2013, 2, 27), 'number': 4L, 'name': u'Ricky', 'id': 84L}

What I have been tried

        pickup_records = []
        for tmpPickUp in pickup:
            pickup_date=tmpPickUp.pickup_date
            pickup_time=tmpPickUp.pickup_time

            pickup_id = tmpPickUp.id
            pickup_name=tmpPickUp.customer_name
            pickup_number=tmpPickUp.pieces
            print pickup_date,pickup_time,pickup_id,pickup_name,pickup_number
            record = {"name":pickup_name, "id":pickup_id,"time":pickup_date,"number":pickup_number,"status":"1"}
            print record
            pickup_records.append(record)

        #pickup_records = json.dumps(pickup_records) 
        pickup_records = json.dumps(pickup_records, indent=4) 
        pickup_response={"pickup":pickup_records}
        return HttpResponse(pickup_response, content_type="application/json") 

EDIT 1

            for tmpPickUp in pickup:
                pickup_date=tmpPickUp.pickup_date
                pickup_time=tmpPickUp.pickup_time

                pickup_id = tmpPickUp.id
                pickup_name=tmpPickUp.customer_name
                pickup_number=tmpPickUp.pieces
                print pickup_date,pickup_time,pickup_id,pickup_name,pickup_number
                record = {"name":pickup_name, "id":pickup_id,"time":pickup_date,"number":pickup_number,"status":"1"}
                print record
                pickup_records.append(record)

            pickup_response={"records":pickup_records}
            print "before pickup+records",pickup_response 
            #pickup_records = json.dumps( pickup_response, sort_keys=True, indent=4)
            print "after pickup+records"  
            #pickup_response={"pickup":pickup_records}
            print "after pickup+response"
            return HttpResponse(pickup_response, content_type="application/json")

LOG RESPONSE

before pickup+records {'records': [{'status': '1', 'time': datetime.date(2013, 2, 27), 'number': 4L, 'name': u'Dr Ayurveda Delhi', 'id': 83L}, {'status': '1', 'time': datetime.date(2013, 2, 27), 'number': 4L, 'name': u'Callmate India', 'id': 84L}]}

I suppose I am making mistakes on return HttpResponse(pickup_response, content_type="application/json") Please correct me

3
  • additional: pickup_records = json.dumps(pickup_records, indent=4) Commented Mar 6, 2013 at 6:41
  • You don't like the spacing? Commented Mar 6, 2013 at 6:43
  • can you arrange your forloop? Commented Mar 6, 2013 at 6:45

4 Answers 4

12

Here is the final working code

        pickup_dict = {}
        pickup_records=[]


        for tmpPickUp in pickup:
                pickup_date=tmpPickUp.pickup_date
                pickup_time=tmpPickUp.pickup_time

                pickup_id = tmpPickUp.id
                pickup_name=tmpPickUp.customer_name
                pickup_number=tmpPickUp.pieces
                print pickup_date,pickup_time,pickup_id,pickup_name,pickup_number
                record = {"name":pickup_name, "id":pickup_id,"number":pickup_number,"status":"1","time":"time"}
                print record
                pickup_records.append(record)

        pickup_dict["pickup"]=pickup_records


        return JsonResponse(pickup_dict)
Sign up to request clarification or add additional context in comments.

Comments

2

I think you need to make sure you're declaring pickup_records as a list, and then check the way you're calling json.dumps.

pickup_records = []
for tmpPickUp in pickup:
    pickup_date=tmpPickUp.pickup_date
    pickup_time=tmpPickUp.pickup_time
    pickup_id = tmpPickUp.id
    pickup_name=tmpPickUp.customer_name
    pickup_number=tmpPickUp.pieces
    print pickup_date,pickup_time,pickup_id,pickup_name,pickup_number
    record = {"name":pickup_name, "id":pickup_id,"time":pickup_date,"number":pickup_number,"status":"1"}
    pickup_records.append(record)
pickup_records = json.dumps({'pickups': pickup_records}, indent=4) 
pickup_response={"pickup":pickup_records}
return HttpResponse(pickup_response, content_type="application/json")

UPDATE

I've run the following in a console - (I think the error must be with your TmpPickUp items) -

>>> import json
>>> records = []
>>> for i in ["","",""]:
...     record = {"name":i, "id":i,"time":i,"number":i,"status":i}
...     records.append(record)
... 
>>> print json.dumps({'pickups': records}, indent=4)
{
    "pickups": [
        {
            "status": "", 
            "time": "", 
            "number": "", 
            "name": "", 
            "id": ""
        }, 
        {
            "status": "", 
            "time": "", 
            "number": "", 
            "name": "", 
            "id": ""
        }, 
        {
            "status": "", 
            "time": "", 
            "number": "", 
            "name": "", 
            "id": ""
        }
    ]
}

4 Comments

What's the error you're getting? Is it the layout that your having trouble with or is the structure of the json object itself?
I suppose it is facing error on pickup_records = json.dumps({'pickups': pickup_records}, indent=4) as print statement after this is not being printed
(you know there's no print statement after that line in my code or your code?)
This solution works, tried it myself with a different dataset
0
from django.utils import simplejson

pickup_records = []
for tmpPickUp in pickup:
    pickup_records.append({ "id": tmpPickUp.id })
    pickup_records.append({ "name": tmpPickUp.customer_name })
    pickup_records.append({ "number": tmpPickUp.pieces })
    pickup_records.append({ "time": tmpPickUp.pickup_time })
    pickup_records.append({ "status": "1" })

return HttpResponse(simplejson.dumps(pickup_records, indent=4), 
                    mimetype="application/json") 

Or maybe this would help you: https://github.com/praekelt/django-generate

Comments

0

At the first you should write your own serializer for datetime.date objects:

import datetime
class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.date):
            return obj.strftime('%m-%d-%Y')
        return json.JSONEncoder.default(self, obj)

after that you can use it:

json.dumps(d, cls=CustomEncoder)
'{"status": "1", "id": 83, "number": 4, "name": "Dr  John", "time": "02-27-2013"}'

so you finale code is:

resp = [{'status': '1', 'time': datetime.date(2013, 2, 27), 'number': 4L, 'name': u'Dr  John',   'id': 83L}{'status': '1', 'time': datetime.date(2013, 2, 27), 'number': 4L, 'name': u'Ricky', 'id': 84L}]
finale_struct = {'products':[]}
for res in resp:
    finale_struct['products'].append(json.dumps(res, cls=CustomEncoder))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.