Skip to content Skip to sidebar Skip to footer

Django Rest Framework: Loop Inside Json Object

Hi Guys I'm new to Django and Python... I'm using REST Framework to develop some webservices. I want to loop through all the orders of a JSON item. The request from javascript is d

Solution 1:

You've not only constructed your JSON object in an unnecessarily verbose and complex way, you're also using the wrong data structure. If you want to iterate something, it should be an array (which maps to a list in Python), not an object (which maps to a dict). Your JS code should look like this:

JSONObject.Orders = [];
JSONObject.Orders.push({id: 1, Name: 'Name1', Description: 'Description1'});
JSONObject.Orders.push({id: 2, Name: 'Name2', Description: 'Description1'});
JSONObject.Orders.push({id: 3, Name: 'Name3', Description: 'Description1'});

(You could actually make that more compact by defining the objects inline with the array, but this is at least clearer for now.)

Now, it's simple to iterate in Python:

for obj in jsondata['Orders']:
    ...

Solution 2:

Since you write you have a Serializer for Order I assume it is also a model on your backend and you would like to store it in the database. In that case I would not bother to manually deserialize the list of orders but let django-restframework unpack the nested child objects along with the parent.

Have a look here: https://stackoverflow.com/a/28246994/640916

Post a Comment for "Django Rest Framework: Loop Inside Json Object"