Laravel 4 JSON Output formatting
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.
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
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);
相同的答案,但与JSON内容类型(如问题中的示例):
return Response::make(json_encode(array(
'status' => 200,
'posts' => $post->toArray()
), JSON_PRETTY_PRINT))->header('Content-Type', "application/json");
链接地址: http://www.djcxy.com/p/47276.html
上一篇: 如何用PHP实现JSON漂亮打印
下一篇: Laravel 4 JSON输出格式