Django Parse Post Request data (JsonArray)

南楼画角 提交于 2019-12-08 07:02:25

问题


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 ??


回答1:


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'



回答2:


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:
            ...


来源:https://stackoverflow.com/questions/43863269/django-parse-post-request-data-jsonarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!