简体   繁体   English

Laravel 4 JSON输出格式

[英]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. 使用上面的代码我以json格式返回数据。
I have seen other api's that return json giving it back in formatted view. 我已经看到其他api的返回json在格式化视图中返回它。
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? 如何使用laravel以格式化方式生成json?


update 更新

I cannot test the code yet until I tomorrow. 直到明天我才能测试代码。 So I'll accept the answer tom. 所以我会接受汤姆的答案。

But this is the api 但这是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. 目前的4.2版本是可能的。

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

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

I don't think Laravel allows you to format the JSON output. 我不认为Laravel允许您格式化JSON输出。 However, you can do it using json_encode() 's JSON_PRETTY_PRINT constant (available since PHP 5.4.0). 但是,您可以使用json_encode()JSON_PRETTY_PRINT常量(从PHP 5.4.0开始提供)来实现。 Here's how: 这是如何做:

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

return json_encode($array, JSON_PRETTY_PRINT);

The same answer but with the json content-type (like the example in the question): 相同的答案,但使用json内容类型(如问题中的示例):

return Response::make(json_encode(array(
    'status' => 200,
    'posts' => $post->toArray()
), JSON_PRETTY_PRINT))->header('Content-Type', "application/json");

This is (to my knowledge) a server-side setting. 这是(据我所知)服务器端设置。 Like xDebug will format it like that (also colours it). 像xDebug一样将它格式化(也为它着色)。

By default, JSON is a single string. 默认情况下,JSON是单个字符串。 And isn't related to Laravel or any other framework. 并且与Laravel或任何其他框架无关。

If you're using PHP 5.4+ You could use JSON_PRETTY_PRINT 如果您使用的是PHP 5.4+,则可以使用JSON_PRETTY_PRINT

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

Untested and you could look in Laravel api if it's possible to use Response::json() for it. 未经测试,如果可以使用Response :: json(),你可以查看Laravel api。

在Laravel 5.2中,您可以使用帮助程序使用类似的方法

return response()->json($data=[], $status=200, $headers=[], $options=JSON_PRETTY_PRINT)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM