JavaScript JSON pretty print

JavaScript JSON 漂亮打印教程展示了如何在 JavaScript 中漂亮地打印 JSON 数据。漂亮的印刷是一种风格格式,包括缩进和着色。

JSON(JavaScript 对象表示法) 是一种轻量级数据交换格式。人类很容易读写,机器很容易解析和生成。 JSON 的官方 Internet 媒体类型是application/json。 JSON文件扩展名为.json

JSON.字符串化

JSON.stringify 函数将 JavaScript 对象或值转换为 JSON 字符串。我们可以使用该函数来漂亮地打印 JSON 输出。请注意,在终端上,console.logconsole.dir 函数会自动漂亮地打印 JSON 数据。在支持彩色输出的终端上,输出也是彩色的。

Web 浏览器不会自动漂亮地打印 JSON 输出;我们可以使用 JSON.stringify 美化 JSON 输出。

使用 JSON.stringify 的 JS JSON 漂亮打印

JSON.stringify 函数有一个空格选项,它会在输出的 JSON 字符串中插入空格以提高可读性。空间的最大值为 10;小于 1 的值不提供空间。

let data = {
    'username': 'John Doe',
    'email': 'john.doe@example.com',
    'state': 'married',
    'profiles': [
        {'name': 'jd7', 'job': 'actor' },
        {'name': 'johnd7', 'job': 'spy'}
    ],
    'active': true,
    'employed': true
};

console.log(JSON.stringify(data, null, 2));

在示例中,我们向 JSON 输出添加了 2 个空格字符。我们不使用替换器,所以我们传递 null 作为第二个参数。

$ node stringify.js 
{
  "username": "John Doe",
  "email": "john.doe@example.com",
  "state": "married",
  "profiles": [
    {
      "name": "jd7",
      "job": "actor"
    },
    {
      "name": "johnd7",
      "job": "spy"
    }
  ],
  "active": true,
  "employed": true
}

在以下示例中,我们从虚假服务中获取用户。我们使用 axioslibrary 来获取用户。使用npm i axios安装它。

const axios = require('axios');

async function makeGetRequest() {

  let res = await axios.get('https://jsonplaceholder.typicode.com/users/2');

  let data = res.data;
  console.log(JSON.stringify(data, null, 4));
}

makeGetRequest();

我们使用伪造的 API https://jsonplaceholder.typicode.com/users/2 URL 获取单个用户。我们使用四个空格进行缩进。

$ node get_user.js 
{
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "Shanna@melissa.tv",
    "address": {
        "street": "Victor Plains",
        "suite": "Suite 879",
        "city": "Wisokyburgh",
        "zipcode": "90566-7771",
        "geo": {
            "lat": "-43.9509",
            "lng": "-34.4618"
        }
    },
    "phone": "010-692-6593 x09125",
    "website": "anastasia.net",
    "company": {
        "name": "Deckow-Crist",
        "catchPhrase": "Proactive didactic contingency",
        "bs": "synergize scalable supply-chains"
    }
}

在下一个示例中,我们在浏览器中使用fetch 函数检索数据。我们用JSON.stringify 美化输出。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <script>
        fetch('https://jsonplaceholder.typicode.com/todos/1')
            .then(response => response.json())
            .then(json =>
                document.body.appendChild(document.createElement('pre')).innerHTML = JSON.stringify(json, null, 4));
    </script>
</body>

</html>

我们从测试网站获取一个 todo 对象。

在本文中,我们在 JavaScript 中美化了 JSON 输出。

列出 JavaScript 教程。

赞(0) 打赏

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏