ZetCode

JavaScript JSON 美化打印

最后修改于 2023 年 10 月 18 日

在本文中,我们将展示如何在 JavaScript 中美化打印 JSON 数据。美化打印是一种样式格式,包括缩进和着色。

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

JSON.stringify

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

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

使用 JSON.stringify 美化打印 JS JSON

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

stringify.js
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
}

在下面的示例中,我们从一个假服务中获取一个用户。我们使用 axios 库来获取用户。使用 npm i axios 安装它。

get_user.js
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 美化输出。

test.html
<!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 对象。

来源

JSON.stringify 文档

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

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。到目前为止,我撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

查看 所有 JavaScript 教程。