JavaScript JSON 美化打印
最后修改于 2023 年 10 月 18 日
在本文中,我们将展示如何在 JavaScript 中美化打印 JSON 数据。美化打印是一种样式格式,包括缩进和着色。
JSON (JavaScript 对象表示法) 是一种轻量级的数据交换格式。它易于人类阅读和编写,也易于机器解析和生成。 JSON 的官方互联网媒体类型是 application/json。 JSON 文件扩展名是 .json。
JSON.stringify
JSON.stringify 函数将 JavaScript 对象或值转换为 JSON 字符串。我们可以使用该函数来美化打印 JSON 输出。请注意,在终端上,console.log 和 console.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
}
在下面的示例中,我们从一个假服务中获取一个用户。我们使用 axios 库来获取用户。使用 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 输出。