ZetCode

JavaScript JSON.stringify

最后修改于 2023 年 10 月 18 日

在本文中,我们将展示如何将 JavaScript 对象转换为 JSON 字符串。

JSON

JSON (JavaScript 对象表示法) 是一种轻量级的数据交换格式。人们可以轻松地读取和编写 JSON。创建用于解析和生成 JSON 的算法也很容易。JSON 的官方互联网媒体类型是 application/json。JSON 文件的扩展名为 .json

JavaScript 提供了以下用于处理 JSON 的方法

JS JSON.stringify

JSON.stringify 方法将 JavaScript 对象或值转换为 JSON 字符串。如果指定了替换函数/数组,它可以选择修改或过滤值。

let json = JSON.stringify(value [, replacer, space])

value 是要转换为 JSON 字符串的值。替换器可以是一个修改字符串化过程行为的函数,也可以是一个作为过滤器使用的数组,用于包含在 JSON 字符串中的值的属性。

JSON.stringify 简单值

在第一个例子中,我们将简单值字符串化。

simple_values.js
console.dir(JSON.stringify(1));
console.dir(JSON.stringify(5.9));
console.dir(JSON.stringify(true));
console.dir(JSON.stringify(false));
console.dir(JSON.stringify('falcon'));
console.dir(JSON.stringify("sky"));
console.dir(JSON.stringify(null));

该示例将简单值字符串化,包括数字、布尔值和字符串。

$ node simple_values.js 
'1'
'5.9'
'true'
'false'
'"falcon"'
'"sky"'
'null'

JSON.stringify 对象

在下一个例子中,我们将对象字符串化。

objects.js
console.dir(JSON.stringify({ x: 5, y: 6 }));
console.dir(JSON.stringify(new Number(6)));
console.dir(JSON.stringify(new String('falcon'))); 
console.dir(JSON.stringify(new Boolean(false)));
console.dir(JSON.stringify(new Date(2020, 0, 6, 21, 4, 5)));
console.dir(JSON.stringify(new Int8Array([1, 2, 3])));
console.dir(JSON.stringify(new Int16Array([1, 2, 3])));
console.dir(JSON.stringify(new Int32Array([1, 2, 3])));
console.dir(JSON.stringify({ x: 2, y: 3, toJSON() { return this.x + this.y; }}));

该示例将简单的自定义和内置对象转换为 JSON 字符串。

$ node objects.js 
'{"x":5,"y":6}'
'6'
'"falcon"'
'false'
'"2020-01-06T20:04:05.000Z"'
'{"0":1,"1":2,"2":3}'
'{"0":1,"1":2,"2":3}'
'{"0":1,"1":2,"2":3}'
'5'

JSON.stringify 对象数组

下一个示例将对象数组转换为 JSON 字符串。

stringify.js
let users = [
    {
        id: 1,
        first_name: 'Robert',
        last_name: 'Schwartz',
        email: 'rob23@gmail.com'
    },
    {
        id: 2,
        first_name: 'Lucy',
        last_name: 'Ballmer',
        email: 'lucyb56@gmail.com'
    },
    {
        id: 3,
        first_name: 'Anna',
        last_name: 'Smith',
        email: 'annasmith23@gmail.com'
    }
];

let data = JSON.stringify(users, null, 2);

console.log(typeof data);
console.log(typeof users);
console.log('------------------');
console.dir(data);
console.log('------------------');
console.dir(users);

在这个例子中,我们有一个用户数组。我们使用 JSON.stringify 函数将该数组转换为 JSON 字符串。

node stringify.js 
string
object
------------------
'[\n' +
  '  {\n' +
  '    "id": 1,\n' +
  '    "first_name": "Robert",\n' +
  '    "last_name": "Schwartz",\n' +
  '    "email": "rob23@gmail.com"\n' +
  '  },\n' +
  '  {\n' +
  '    "id": 2,\n' +
  '    "first_name": "Lucy",\n' +
  '    "last_name": "Ballmer",\n' +
  '    "email": "lucyb56@gmail.com"\n' +
  '  },\n' +
  '  {\n' +
  '    "id": 3,\n' +
  '    "first_name": "Anna",\n' +
  '    "last_name": "Smith",\n' +
  '    "email": "annasmith23@gmail.com"\n' +
  '  }\n' +
  ']'
------------------
[
  {
    id: 1,
    first_name: 'Robert',
    last_name: 'Schwartz',
    email: 'rob23@gmail.com'
  },
  {
    id: 2,
    first_name: 'Lucy',
    last_name: 'Ballmer',
    email: 'lucyb56@gmail.com'
  },
  {
    id: 3,
    first_name: 'Anna',
    last_name: 'Smith',
    email: 'annasmith23@gmail.com'
  }
]

JSON.stringify 替换器示例

在下面的示例中,我们使用替换器函数来转换数据。

replacer.js
function replacer(key, value) {
  if (typeof value === 'string') {
    return value.toUpperCase();
  }
  return value;
}

var user = { name: 'John Doe', occupation: 'gardener', age: 34, 
  dob: new Date('1992-12-31') };

console.dir(JSON.stringify(user, replacer));

替换器函数将 user 对象中的所有字符串转换为大写。

$ node replacer.js 
'{"name":"JOHN DOE","occupation":"GARDENER","age":34,"dob":"1992-12-31T00:00:00.000Z"}'

另一种形式的替换器是一个数组,它过滤掉对象属性。

replacer2.js
var user = { name: 'John Doe', occupation: 'gardener', dob: new Date('1992-12-31') };

console.dir(JSON.stringify(user, ['name', 'occupation']));

在这个例子中,我们只包含在字符串化过程中在替换器数组中指定的属性:nameoccupation

$ node replacer2.js 
'{"name":"John Doe","occupation":"gardener"}'

JSON.stringify 美化打印

space 选项用于美化输出。请注意,console.logconsole.dir 已经美化了输出。

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>

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

来源

JSON.stringify 文档

在本文中,我们使用 JSON.stringify 函数将 JavaScript 对象转换为 JSON 字符串。

作者

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

查看 所有 JavaScript 教程。