将对象数组 POST 到 REST API [英] POST array of objects to REST API

查看:25
本文介绍了将对象数组 POST 到 REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计应该能够接受对象数组的 REST API,比如说

<预><代码>[{'name': '爱丽丝',年龄":15},{'name': '鲍勃',年龄":20},...]

确实,API 可以有一个接受单个对象的方法,该方法将被循环调用.但是,出于性能原因,我希望在一个请求中 POST 多个对象.

这样做最优雅的方式是什么?目前我唯一的想法就是使用JSON,比如:

post_params = { 'data' : to_json_string([ { 'name' : 'Alice', 'age' : 15 },{'姓名':'鲍勃','年龄':20},...])};后(网址,后参数);

这样可以吗,还是我应该使用一些完全不同的方法?

解决方案

无需将数组包装在另一个具有 data 属性的对象中.数组本身是有效的 JSON:

post_params = JSON.stringify([ { 'name' : 'Alice', 'age' : 15 },{'姓名':'鲍勃','年龄':20},...]);后(网址,后参数);

只要确保你的 API 也需要这个数组.

I'm designing REST API that should be able to accept array of objects, say

[
 {
   'name': 'Alice',
   'age': 15
 },
 {
   'name': 'Bob',
   'age': 20
 },
 ...
]

Indeed, the API could have a method for accepting single object, which would be called in cycle. However, for performance reasons, I wish to POST multiple objects in one request.

What is the most elegant way of doing so? So far my only idea is to use JSON, such as:

post_params = { 'data' : to_json_string([ { 'name' : 'Alice', 'age' : 15 },
                                          { 'name' : 'Bob',   'age' : 20 },
                                          ...
                                        ])
              };
post(url, post_params);

Is this OK, or should I use some completely different approach?

解决方案

There is no need to wrap the array in another object with a data property. The array by itself is valid JSON:

post_params = JSON.stringify([ { 'name' : 'Alice', 'age' : 15 },
                               { 'name' : 'Bob',   'age' : 20 },
                                  ...
                             ]);
post(url, post_params);

Just make sure your API expects this array as well.

这篇关于将对象数组 POST 到 REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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