madhuri H R
madhuri H R

Reputation: 719

Django Parse Post Request data (JsonArray)

I have a model Example with 3 fields.

class Example(models.Model):
      name = models.CharField(max_length=200, null=False, blank=False)
      number = models.CharField(max_length=200, null=False, blank=False)
      address = models.CharField(max_length=200)`

I have a Post API (rest framework). This would have array of objects. I want to parse this array and store each object in my database. This is the Views.py

class PostExample(APIView):
    def post(self, request, format=None):
        example_records = request.POST["example_data"]
        print example_records

Here "example_data" is the key and value will be an array. Example value:

[
  {
    "name": "test",
    "address": "address",
    "number": 123456789
  },
  {
    ...
  }
] 

I am unable to loop through "example_records". "example_records" prints the array but not able to get each object from this. How to achieve this ??

Upvotes: 1

Views: 5229

Answers (2)

Michael Rigoni
Michael Rigoni

Reputation: 1966

request.POST is the raw data received during POST, which is a json string. You could use the json module as suggested by some users but Django Rest Framework does the work for you: request.data. That is the whole point of using a framework like DRF.

class PostExample(APIView):
    def post(self, request, format=None):
        example_records = request.data["example_data"]
        for record in example_records:
            ...

Upvotes: 0

akash karothiya
akash karothiya

Reputation: 5950

You can use json module here. First convert your example_records string data into json object and then parse Example value and finally iterate through all.

import json
data = '''{"Example value":[{"name":"test1","address":"address1","number":123456789},{"name":"test2","address":"address2","number":123456789}]}'''
jobject = json.loads(data)
for val in jobject['Example value']:
    print(val)

{'address': 'address1', 'name': 'test1', 'number': 123456789}
{'address': 'address2', 'name': 'test2', 'number': 123456789}

Then you can simply extract values by passing its corresponding key, For example :

print(val['name'])
'test1'
'test2'

Upvotes: 1

Related Questions