Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 JSON Output formatting

Tags:

json

php

laravel

return Response::json(array(
    'status' => 200,
    'posts' => $post->toArray()
), 200);

Using the code above I returned data in json format.
I have seen other api's that return json giving it back in formatted view.
Like:

http://api.steampowered.com/ISteamNews/GetNewsForApp/v0002/?appid=440&count=3&maxlength=300&format=json

But mine is returning it in one line. How do I generate the json in a formatted way with laravel?


update

I cannot test the code yet until I tomorrow. So I'll accept the answer tom.

But this is the api

http://laravel.com/api/class-Illuminate.Support.Facades.Response.html

and the parameters are,

$data
$status
$headers

update

Actually I modified the response class of illuminate to have that constant.

like image 222
madziikoy Avatar asked Dec 19 '13 10:12

madziikoy


2 Answers

It is possible in current 4.2 version.

Response::json($data=[], $status=200, $headers=[], $options=JSON_PRETTY_PRINT);

https://github.com/laravel/framework/commit/417f539803ce96eeab7b420d8b03f04959a603e9

like image 125
Travis Miller Avatar answered Sep 29 '22 23:09

Travis Miller


I don't think Laravel allows you to format the JSON output. However, you can do it using json_encode()'s JSON_PRETTY_PRINT constant (available since PHP 5.4.0). Here's how:

$array = array(
    'status' => 200,
    'posts' => $post->toArray()
);

return json_encode($array, JSON_PRETTY_PRINT);
like image 33
Amal Murali Avatar answered Sep 29 '22 22:09

Amal Murali