Django Parse Post Request数据(JsonArray) [英] Django Parse Post Request data (JsonArray)

查看:70
本文介绍了Django Parse Post Request数据(JsonArray)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含3个字段的模型示例。

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)`

我有一个Post API(其余框架)。这将具有对象数组。我想解析此数组并将每个对象存储在数据库中。这是Views.py

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

这里 example_data是键,值将是一个数组。值示例:

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

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

我无法遍历 example_records。 example_records打印数组,但无法从中获取每个对象。

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

推荐答案

您可以在此处使用 json 模块。首先将您的 example_records 字符串数据转换为 json 对象,然后解析示例值并最终遍历所有对象。

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}

然后,您可以通过传递相应的<$来提取 c $ c> key ,例如:

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

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

这篇关于Django Parse Post Request数据(JsonArray)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆