简体   繁体   English

如何在 JSON 响应中返回数组而不是对象?

[英]How to return an array instead of object in JSON response?

I've one working REST API developed using Slim PHP framework.我有一个使用 Slim PHP 框架开发的有效 REST API。

It's working absolutely fine.它工作得很好。

The only issue is when there is no error present ie an array $errors is empty it comes as an array in JSON response but when the array $errors contains any error like $errors['user_name'] then it comes as an object in JSON response.唯一的问题是当不存在错误时,即数组$errors为空时,它作为 JSON 响应中的数组$errors但当数组$errors包含任何错误时,如$errors['user_name']那么它作为 JSON 中的对象出现回复。

Actually I want to return the array when error is present.实际上我想在出现错误时返回数组。 How should I do this?我该怎么做? Can someone please help me in this regard?有人可以在这方面帮助我吗?

Thanks in advance.提前致谢。

When your $errors is not empty, pass it through json_encode and echo it.当您的$errors不为空时,通过json_encode传递它并回显它。 It will give you JSON object in return, then convert JSON object into JavaScript array.它会给你 JSON 对象作为回报,然后将 JSON 对象转换为 JavaScript 数组。 (see the following code.) (请参阅以下代码。)

var o = {"0":"1","1":"2","2":"3","3":"4"}; // your response object here 

var arr = Object.keys(o).map(function(k) { return o[k] });

console.log(arr);

Recently got a close issue with Symfony's JsonResponse::create()最近有一个与 Symfony 的JsonResponse::create()密切相关的问题

Turns out arrays with index not starting at 0 will be encoded into objects, as well as arrays with "holes" , and probably any array with at least one non-int key .原来索引不是从 0 开始的数组将被编码到对象中,以及带有 "holes" 的数组,可能还有至少一个非 int key 的任何数组。

In other word, arrays with anything else than consecutive numeric keys starting from index 0 seem to be encoded as object.换句话说,除了从索引 0 开始的连续数字键之外的任何其他数组似乎都被编码为对象。

I guess this is designed to avoid sending big empty arrays when you map a handful of datas with big indices like [14334, 839493, 246193], and is probably documented somewhere.我猜这是为了避免在您映射具有大索引(如 [14334、839493、246193])的少量数据时发送大的空数组,并且可能在某处记录。

Learning if this is a Symfony of json_encode behavior from comments would be welcomed addition :)欢迎从评论中了解这是否是 json_encode 行为的 Symfony 补充:)


Note : Even if you return an array, it seems necessary to wrap it in an object for GET request to prevent some XSSI and JSON-JavaScript Hijacking .注意:即使您返回一个数组,似乎也有必要将其包装在一个对象中以供 GET 请求使用,以防止某些 XSSI 和 JSON-JavaScript 劫持

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM