简体   繁体   English

如何使用PHP正确输出JSON数据

[英]How to output JSON data correctly using PHP

I'm developing an Android app, and for the API I'm sending my requests to a URL that should return JSON data.我正在开发一个 Android 应用程序,对于 API,我将我的请求发送到一个应该返回 JSON 数据的 URL。

This is what I'm getting in my output:这是我在输出中得到的:我的回复

And I'd like it to be displayed as Twitter response:我希望它显示为 Twitter 响应:

Twitter 的 JSON 响应

I'm assuming my response is not being parsed by the JSON Formatter Chrome extension because it's encoded badly, thus my app can't get the values I need.我假设我的响应没有被 JSON Formatter Chrome 扩展程序解析,因为它编码错误,因此我的应用程序无法获得我需要的值。

Here's my PHP code:这是我的 PHP 代码:

<?php

$response = array();

if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) 
{

    $name = $_POST['name'];
    $price = $_POST['price'];
    $description = $_POST['decription'];

    require_once __DIR__ . '/db_connect.php';

    $db = new DB_CONNECT();

    $result = mysql_query("INSER INTO products(name, price, description) VALUES('$name', '$price', '$description')");

    if ($result) {
        $response["success"] = 1;
        $response["message"] = "Product successfully created.";

        echo json_encode($response);
    } else {

        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred!";

        echo json_encode($response);
        }
} else {

    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    echo json_encode($response);

}

?>

I want to know how to display the JSON data correctly so that JSON Formatter and my android App can parse it correctly.我想知道如何正确显示 JSON 数据,以便 JSON Formatter 和我的 android 应用程序可以正确解析它。

Your problem is actually very easy to solve.你的问题其实很容易解决。 The Chrome JSON Formatter plugin only formats your output if the Content-Type header is set to application/json.如果 Content-Type 标头设置为 application/json,Chrome JSON Formatter 插件只会格式化您的输出。

The only thing you need to change in your code is to use header('Content-Type: application/json');您唯一需要在代码中更改的是使用header('Content-Type: application/json'); in your PHP code, before returning the json-encoded data.在您的 PHP 代码中,在返回 json 编码的数据之前。

PHP's json_encode function takes a second argument, for $options . PHP 的json_encode函数采用第二个参数,用于$options Here you can use JSON_PRETTY_PRINT to print it like you see in the Twitter API在这里您可以使用JSON_PRETTY_PRINT来打印它,就像您在 Twitter API 中看到的那样

Eg例如

echo json_encode($my_array, JSON_PRETTY_PRINT);

You can pass an argument to the json_encode function like this :您可以像这样将参数传递给json_encode函数:

echo json_encode($response, JSON_PRETTY_PRINT);

PHP 5.2.0 => http://php.net/manual/en/function.json-encode.php PHP 5.2.0 => http://php.net/manual/en/function.json-encode.php

Your JSON should be like your first image;你的 JSON 应该像你的第一张图片; All in one line squished together.一行一行都挤在一起。 You can pass your output to jsonlint.com which can help you find your typo/bad data.您可以将输出传递给 jsonlint.com,它可以帮助您找到拼写错误/错误数据。 ALL the current other answers could help you solve your issue as well.所有当前的其他答案也可以帮助您解决问题。 they all give you different options to format your output if you really want to do that.如果您真的想这样做,它们都会为您提供不同的选项来格式化输出。

Here's another way for you to display your JSON in HTML.这是您在 HTML 中显示 JSON 的另一种方式。

If you wrap your response in HTML < pre > tags you'll keep the white space format.如果您将响应包装在 HTML < pre > 标签中,您将保留空白格式。

For example, I use jQuery to get some json data and in jQuery take the json object and put it directly in a < pre > that's formatted例如,我使用 jQuery 获取一些 json 数据,并在 jQuery 中获取 json 对象并将其直接放在格式化的 <pre> 中

<pre class="output" style="text-align:left; width:80%; margin:0 auto">[ results ]</pre>

I use我用

$('.output').html( JSON.stringify(data,null,4) );

This will take your json return, format it with spaces with the HTML < pre > can use to format it like you want to see.这将返回您的 json,用空格格式化它,HTML < pre > 可以用来格式化它,就像你想看到的那样。

If you want to have your json color coded... you can use http://prismjs.com/ or any other highlighting system...如果你想让你的 json 颜色编码......你可以使用http://prismjs.com/或任何其他突出显示系统......

Your JSON response is already in good shape.您的 JSON 响应已经处于良好状态。 The reponse you are viewing is in Chrome browser.您正在查看的响应是在 Chrome 浏览器中。 Thats why it looks like that .这就是为什么它看起来像那样。 If you add below line in yoru code如果您在 yoru 代码中添加以下行

var_dump($response); and then rightclick -> view source in chrome brower , you will see the tree structure.然后右键单击 -> 在 chrome 浏览器中查看源代码,您将看到树结构。 Anyway you can copy your JSON reponse and check the validy here无论如何,您可以复制您的 JSON 响应并在此处检查验证

The same thing I belive first when I saw it in chrome .当我在 chrome 中看到它时,我首先相信它。 It happens to me also.它也发生在我身上。

just Add pre Tag -->只需添加预标签-->

<pre><?php  ---you`r code---     ?> </pre>

and

echo json_encode($response, JSON_PRETTY_PRINT);

after adding pre-Tag and JSON_PRETTY_PRINT I'm sure your Problem will solve.添加 pre-Tag 和 JSON_PRETTY_PRINT 后,我相信您的问题会解决。

Laravel Laravel

Setting header header('Content-Type: application/json'); 设置标题header('Content-Type: application/json'); or json PRETTY_PRINT didn't work? 或者json PRETTY_PRINT不起作用?

A little bit of css is what you need white-space: pre-wrap; 一点点css是你需要white-space: pre-wrap;

You are dumping json to a blank page from controller or router? 您是从控制器或路由器将json转储到空白页面?

Route::get('/print-json', function (Request $request) {
    echo '<style>body{ white-space: pre-wrap; }</style>';
    echo json_encode([
        'IP' => $request->getClientIp(),
        'Route' => $request->route(),
    ], JSON_PRETTY_PRINT);
});

Output: 输出:

{
    "IP": "127.0.0.1",
    "Route": {
        "uri": "showArray",
        "methods": [
            "GET",
            "HEAD"
        ],
        "action": {
            "middleware": "web",
            "uses": {},
            "namespace": "App\\Http\\Controllers",
            "prefix": null,
            "where": []
        },
        "isFallback": false,
        "controller": null,
        "defaults": [],
        "wheres": [],
        "parameters": [],
        "parameterNames": [],
        "computedMiddleware": [
            "web"
        ],
        "compiled": {}
    }
}

All you have to do is to add a second argument to the json_encode method like this.您所要做的就是像这样向json_encode方法添加第二个参数。

echo json_encode($response_date, JSON_PRETTY_PRINT);

or要么

print json_encode($response_date, JSON_PRETTY_PRINT);

You can visit this link to read more on how to use json_encode .您可以访问此链接以阅读有关如何使用json_encode

Hope it helps.希望能帮助到你。

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

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