JavaScript JSON.stringify

JavaScript JSON.stringify 教程展示了如何将 JavaScript 对象转换为 JSON 字符串。

JSON

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

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

  • JSON.stringify – 将 JS 对象转换为 JSON
  • JSON.parse – 将 JSON 转换回 JS 对象

JS JSON.stringify

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

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

value 是要转换为 JSON 字符串的值。替换器要么是一个改变字符串化过程行为的函数,要么是一个数组,该数组充当要包含在 JSON 字符串中的值对象属性的过滤器。

JSON.stringify 简单值

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

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 对象

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

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 字符串。

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 函数将数组转换为 JSONstring。

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 函数来转换数据。

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));

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

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

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

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 已经美化了输出。

<!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 函数将 JavaScript 对象转换为 JSON 字符串。

列出所有 JavaScript 教程。

赞(0) 打赏

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

支付宝扫一扫打赏

微信扫一扫打赏