laravel / framework

The Laravel Framework.
https://laravel.com
MIT License
32.42k stars 10.99k forks source link

[Proposal] Pretty print json output #3929

Closed jcwatson11 closed 10 years ago

jcwatson11 commented 10 years ago

Continuing the discussion ticket #3648. I don't think the opt-in option was clearly understood before that ticket was closed.

If the feature defaults to not pretty printing, then there are no concerns for those who want to keep the payload small. If we add an optional feature, we save many developers from having to write a custom Response macro every time they want to implement this.

Sounds like a win-win to me.

For debugging purposes, having the option to read JSON in a pretty-print format is indispensable.

May we please revive this issue?

GrahamCampbell commented 10 years ago

We are now just allowing options to be passed to the encode method. You can pass whatever you like. See http://php.net/manual/en/json.constants.php.

So, in order to pretty print, you'll need to pass JSON_PRETTY_PRINT as an option. Laravel will not do this for you. If you want to pass it only when debug mode is enabled, you'll have to write your own logic for that.

jcwatson11 commented 10 years ago

Thanks for your response. So, or example, would I do something like:

return Response::json($response,JSON_PRETTY_PRINT);

Or would it be something else?

Also, what version (or tag) do I need to be using in order to get this feature?

Thanks again!

GrahamCampbell commented 10 years ago

No. Please just read the source...

I quote from the source... function json($data = array(), $status = 200, array $headers = array(), $options = 0)

This functionality was introduced in laravel 4.1.23, but had an issue that was fixed in 4.1.24.

jcwatson11 commented 10 years ago

Ok. Thanks for your help. So just for the sake of posterity (folks reading this thread later) my call would be:

return Response::json($response, null, null, JSON_PRETTY_PRINT);

Is this correct?

ipalaus commented 10 years ago
return Response::json($response, 200, array(), JSON_PRETTY_PRINT);
GrahamCampbell commented 10 years ago

return Response::json($data, 200, array(), JSON_PRETTY_PRINT);

Please close this. This is not an issue,

jcwatson11 commented 10 years ago

Thanks!

katoba86 commented 7 years ago

In Controller return response()->json($data,200,[],JSON_PRETTY_PRINT);

TimOgilvy commented 7 years ago

Remains undocumented

emadha commented 7 years ago

i still cannot find a way in Laravel to add multiple options to the json return like JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES, best would be (to me now) :

use Illuminate\Support\Facades\Response;

$response = json_encode(
                    [YOUR_ARRAY],
                    JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
            );

return response($response)->header('Content-Type', 'application/json');
tremby commented 7 years ago

@emadha, it's as simple as passing JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES as the fourth argument to the json() call.

TimOgilvy commented 6 years ago

@GrahamCampbell I'm interested in understanding why your view is that people should read the source. Laravel is a framework with reasonable detailed documentation, which takes pride in being efficient and easy to use. Why is "please just read the source" an okay response to this?

From the Laravel Front Page:

Expressive, beautiful syntax. Value elegance, simplicity, and readability? You’ll fit right in. Laravel is designed for people just like you. If you need help getting started, check out Laracasts and our great documentation.

Being condescending to 'noobs' plays well on COD, but not so much on github. I'm confused. I mean if I'm wrong tell me, but it just seems a bit off-the-mark for laravel.

Happy to submit a PR for the docs and add it somewhere appropriate myself, just confused what the ethos is here.

devcircus commented 6 years ago

Any web developer that wants to go the extra step and incorporate features into a site that go beyond what is explained via the basic documentation, should FIRST look to the source itself. There you'll find all answers. As devs, we should be well read in the source of the library or framework that we reach for most often.

jcwatson11 commented 6 years ago

I vote the philosophical aspect of this debate be moved to another channel. :)

tremby commented 6 years ago

Any web developer that wants to go the extra step and incorporate features into a site that go beyond what is explained via the basic documentation, should FIRST look to the source itself. There you'll find all answers. As devs, we should be well read in the source of the library or framework that we reach for most often.

While I don't disagree that reading the source is valuable, using and relying on undocumented features you find in the source code is a terrible idea! You have no guarantee that the feature won't just disappear in the next version, with no deprecation warning or other notification.

devcircus commented 6 years ago

All true as well. Keep in mind that though the majority of the docs were written by Taylor, and practically everything a newcomer needs to get started are there, the docs are open source and maintained by the community. If there are vital missing pieces, please submit a pr. It's on us to make sure the documentation stays up-to-date.

TimOgilvy commented 6 years ago

^ These are the insights I was looking for. Laravel is saving my bacon right now, really appreciate it, and would be keen to contribute useful things, but don't want to be a jerk creating PR's for trivial junk that will annoy people. I'm going to see if I can find an appropriate place to add this to the docs. Gracias.

devcircus commented 6 years ago

Probably not the place for this, but thought it may be helpful......For anyone needing information on how to start submitting pull requests, see this post by Matt Stauffer or this series at Laracasts, if you have an account. This post has good info as well, written by Rob Allen of Zend and Slim fame.

ejlocop commented 6 years ago

In Controller return response()->json($data,200,[],JSON_PRETTY_PRINT);

or in an eloquent collection.

$items = Model::all();
dd($items->toJson(JSON_PRETTY_PRINT));
dapseen commented 5 years ago

In Controller return response()->json($data,200,[],JSON_PRETTY_PRINT);

or in a eloquent collection.

$items = Model::all();
dd($items->toJson(JSON_PRETTY_PRINT));

it still wont remove backslashes in json

$items = Model::all();
dd($items->toJson(200,[],JSON_PRETTY_PRINT`);
robclancy commented 5 years ago

Use a macro

Response::macro('prettyJson', function ($data = [], $status = 200, array $headers = [], $options = JSON_PRETTY_PRINT) {
    return $this->json($data, $status, $headers, $options);
});

response()->prettyJson(['why_you_even_need_it_pretty' => '??']);
xdagee commented 4 years ago

In Controller return response()->json($data,200,[],JSON_PRETTY_PRINT);

or in a eloquent collection.

$items = Model::all();
dd($items->toJson(JSON_PRETTY_PRINT));

it still wont remove backslashes in json

$items = Model::all();
dd($items->toJson(200,[],JSON_PRETTY_PRINT`);

do this instead dd($items->toJson(200, [], JSON_UNESCAPED_SLASHES);

pablorsk commented 3 years ago

Case:

Solution:

return Response::json($data, 200, [], Request::wantsJson() ? 0 : JSON_PRETTY_PRINT);

Json result:

$ curl -H "Accept: application/json"  https://api.saldo.com.ar/json/rates/banco
{"bitcoin":{"bid":5927354.569830435,"ask":4876449.273568469,"currency":"ARS","bid_url":"https:\/\/saldo.com.ar\/a\/banco\/bitcoin","ask_url":"https:\/\/saldo.com.ar\/a\/bitcoin\/banco"},"usdt":{"bid":167.35938588161167,"ask":145.90532150255447,"currency":"ARS","bid_url":"https:\/\/saldo.com.ar\/a\/banco\/usdt","ask_url":"https:\/\/saldo.com.ar\/a\/usdt\/banco"},"dai":{"bid":181.89461443495162,"ask":138.507516916841,"currency":"ARS","bid_url":"https:\/\/saldo.com.ar\/a\/banco\/dai","ask_url":"https:\/\/saldo.com.ar\/a\/dai\/banco"}}

Browser result:

image

joelmellon commented 3 years ago

I wanted to do this for all of my JsonResponses when a request parameter "pretty" was specified by the client. Here's what I ended up with:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class FormatApiResponses
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);

        if ($response instanceof JsonResponse) {
            if ($request->pretty) {
                $response->setEncodingOptions(JSON_PRETTY_PRINT);
            }
        }

        return $response;
    }
}

Then I added this Middleware to my app/Http/Kernel.php:


    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [...],

        'api' => [
            [...],
            'throttle:api',
            \App\Http\Middleware\FormatApiResponses::class,
        ],
    ];