Home > front end >  How to return formatted(pretty) JSON instead of JSON? Or new line JSON instead of inline JSON?(Larav
How to return formatted(pretty) JSON instead of JSON? Or new line JSON instead of inline JSON?(Larav

Time:12-20

While returning data from laravel routes or controllers, they are automatically returned as JSON data. That's cool but reading these data into the web page it's difficult. Because they're inline, and it's hard to identify elements. I know I could use something like: enter image description here

In Firefoxenter image description here

This no work in Google Chrome (in my devices).

CodePudding user response:

If you use the response()->json() method to generate your json response, you can pass in the encoding options in the fourth parameter.

Route::get('usersAsJson', function(){
   return response()->json(DB::table('users')->limit(3)->get(), 200, [], JSON_PRETTY_PRINT);
});

If you plan on doing this in a lot of places, I would suggest defining a new response macro (e.g. prettyJson()) and using that to clean up the code a little bit.

Add this to your AppServiceProvider::boot() method:

Illuminate\Support\Facades\Response::macro('prettyJson', function ($data = [], $status = 200, array $headers = [], $options = 0) {
    return Illuminate\Support\Facades\Response::json($data, $status, $headers, JSON_PRETTY_PRINT | $options);
});

Then you can use the new prettyJson method on your response, and it'll take care of adding in the pretty print option for you (and still retain all the other functionality of the original json() method):

Route::get('usersAsJson', function(){
   return response()->prettyJson(DB::table('users')->limit(3)->get());
});

CodePudding user response:

https://www.php.net/manual/en/json.constants.php#constant.json-pretty-print

return json_decode(DB::table('users')->limit(3)->get(), JSON_PRETTY_PRINT);

  • Related