Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Proposal] Pretty print json output #3929

Closed
jcwatson11 opened this issue Mar 19, 2014 · 25 comments
Closed

[Proposal] Pretty print json output #3929

jcwatson11 opened this issue Mar 19, 2014 · 25 comments

Comments

@jcwatson11
Copy link

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
Copy link
Member

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
Copy link
Author

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
Copy link
Member

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
Copy link
Author

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
Copy link
Contributor

ipalaus commented Mar 19, 2014

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

@GrahamCampbell
Copy link
Member

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

Please close this. This is not an issue,

@jcwatson11
Copy link
Author

Thanks!

@katoba86
Copy link

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

@TimOgilvy
Copy link

Remains undocumented

@emadha
Copy link

emadha commented May 30, 2017

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
Copy link

tremby commented Jul 26, 2017

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

@TimOgilvy
Copy link

TimOgilvy commented Feb 14, 2018

@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
Copy link
Contributor

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
Copy link
Author

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

@tremby
Copy link

tremby commented Feb 14, 2018

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
Copy link
Contributor

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
Copy link

^ 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
Copy link
Contributor

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.

jk3us added a commit to jk3us/docs-1 that referenced this issue Mar 7, 2018
Add that you can pass in a bitmask of options to `toJson()` that gets passed to `json_encode`.

See also laravel/framework#3929
@ejlocop
Copy link

ejlocop commented Jun 19, 2018

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
Copy link

dapseen commented May 1, 2019

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
Copy link
Contributor

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
Copy link

xdagee commented Jan 21, 2020

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
Copy link
Contributor

pablorsk commented May 23, 2021

Case:

  • Pretty response for browser.
  • Minified response for json requests.

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
Copy link
Contributor

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,
        ],
    ];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

15 participants