简体   繁体   中英

How to use Laravel response()->json() to return empty object instead of empty array

In Laravel 5.5

Route::get('/test2', function (){
    $data = (object) [];

    return response()->json($data);

});

it always returns [] rather than {} .


another code:

Route::get('/test2', function (){
    $data = (object) [];

    return json_encode($data);

});

it correctly returns {}


I want to use response()->json() helper to return empty object instead of empty array , is it possible?

这有效:

return response()->json(new stdClass());

One more example, inspired by Hamid Mohayeji answer:

return \response()->json(null);

No need to instantiate stdClass (memory allocation though).

Using dingo/api modifies the answer of the empty array as @kingshark said, but you can make this work without stoping using dingo or modifying anything else than your own response.

Dingo expects the $data to be already encoded as json, so, if you do:

$data = ['message' => 'Lorem Ipsum', 
         'errors' => []];
return response()->json($data);

Will get:

{
    "message": "Lorem Ipsum",
    "errors": []
}

But if you do:

$data = ['message' => 'Lorem Ipsum', 
         'errors' => []];
$data = json_encode($data, JSON_FORCE_OBJECT);
return response()->json($data);

You will get:

{
    "message": "Lorem Ipsum",
    "errors": {}
}

When you return response()->json($data) , it returns a JsonResponse object which includes $data in data field. So when you receive this response, you get the data with the same format(object).

JsonResponse json(string|array $data = [], int $status = 200, array $headers = [], int $options)

When you return json_encode($data) , it will parse the $data and returns a string: "{}" . Only if you decode "{}" , it will become object again.

string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )

Thanks everyone, finally I found the problem: dingo/api .

If I use response()->json($data) in app using dingo/api package, there is a different response handling process. At some point, it will go through \\Dingo\\Api\\Http\\Response::makeFromJson method which decode the response content, then create a new response instance, which changed {} to [] .

If I removed or do not use dingo/api package, response()->json() can work well, at least in Laravel 5.5.

dingo/api override, change and extend large amount of laravel built-in classes and approach in the entire request life cycle, from route to response to exception handling.

This works in Laravel 5.6

Route::get('/test2', function (){
    $data = (object) [];

    return response()->json($data, 200, [], JSON_FORCE_OBJECT);

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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