正如标题所说,如何防止 Laravel 删除输入 json 中的空数组?示例:给定客户端请求
$.ajax({
url: "/test",
data: {
populatedArray: ["Fine, as long as it has >0 elements"],
emptyArray: [], // This property will not be available!
tasks: {
fooTask: {
empty: [],
nullObject: null,
regular: "It should also work for nested"
}
}
},
contentType: "application/json",
});
和 Controller
public function test(Request $request) {
Log::info(json_encode($request->populatedArray));
Log::info(json_encode($request->emptyArray));
}
我收到以下日志消息:
[2018-01-30 12:30:01] local.INFO: ["Fine, as long as it has >0 elements"]
[2018-01-30 12:30:01] local.INFO: null
我希望第二行产生 [] 但它不存在于 $request 对象中??
最佳答案
在将其发送到服务器之前,将数据打包为字符串
$.ajax({
url: "/stimpack/test/",
data: {
myValue: "all good",
populatedArray: ["Fine, as long as it has >0 elements"],
emptyArray: [], // This property will not be available!,
tasks: JSON.stringify({
fooTask: {
empty: [],
nullObject: null,
regular: "Hi all"
}
})
},
contentType: "application/json"
});
接下来,在您的 Controller 中,将字符串解压为对象,如下所示
$inputAsObject = json_decode($request->tasks);
记录它也会显示空数组
Log::info(json_encode($inputAsObject));
另一个好处是您不必担心 Laravel 将所有内容都视为关联数组。这意味着你可以这样做:
Log::info(json_encode($inputAsObject->fooTask->empty));
关于laravel - 如何防止 Laravel 剥离空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48521694/