JavaScript JSON.parse

JavaScript JSON.parse 教程展示了如何将 JSON 字符串解析为 JavaScript 对象。

JSON

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

JS JSON.parse

JSON.parse 方法解析 JSON 字符串并创建由该字符串描述的 JavaScript 值或对象。可以提供一个可选的 reviver 函数,以便在返回结果对象之前对其执行转换。用JSON.stringify进行反向操作。

JSON.parse 值

在第一个示例中,我们将 JSON 字符串解析为 JavaScript 值。

console.log(JSON.parse('-3'));
console.log(JSON.parse('12'));
console.log(JSON.parse('true'));
console.log(JSON.parse('"falcon"'));

该示例解析并打印整数、布尔值和字符串。

$ node parse_values.js
-3
12
true
falcon

JSON.parse 数组

下一个示例将 JSON 数组字符串解析为 JavaScript 数组。

let data = `[
  {
    "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 users = JSON.parse(data);

console.log(typeof users)
console.log('-------------------');
console.log(users[1])
console.log('-------------------');
console.log(users);

我们有一个由用户组成的 JSON 字符串。字符串被解析为 JavaScript 数组。

let users = JSON.parse(data);

数据被解析。

console.log(typeof users)

我们确定返回数据的数据类型。

console.log(users[1])

我们打印第二个用户。

console.log(users);

我们打印整个数组。

$ node parse_array.js 
object
-------------------
{
  id: 2,
  first_name: 'Lucy',
  last_name: 'Ballmer',
  email: 'lucyb56@gmail.com'
}
-------------------
[
  {
    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.parse 嵌套数组

在下一个示例中,我们解析包含嵌套数组的 JSON 数据。

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

let data = JSON.parse(user);

function printValues(obj) {
    for(var k in obj) {
        if(obj[k] instanceof Object) {
            printValues(obj[k]);
        } else {
            console.log(obj[k]);
        };
    }
};

printValues(data);

console.log('-------------------');

Object.entries(data).map((e) => {
    console.log(e);
});

我们使用递归 printValues 函数和 Object.entries 函数遍历已解析的 JSON 对象。

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

JSON.parse reviver函数

JSON.parse 函数可以将可选的 reviver 函数作为第二个参数。它可以在返回结果对象之前对其执行转换。

let data = '{ "name": "John Doe", "dateOfBirth": "1976-12-01", "occupation": "gardener"}';

let user = JSON.parse(data, (k, v) => {

  if (k == "dateOfBirth") {
    return new Date(v);
  } else {
    return v;
  }
});

console.log(user);

在示例中,我们使用 reviver 函数将字符串属性转换为日期。

JSON.字符串化

JSON.stringify 函数将 JavaScript 对象或值转换为 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.parse 函数将JSON 字符串解析为JavaScript 对象。

列出所有 JavaScript 教程。

赞(0) 打赏

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

支付宝扫一扫打赏

微信扫一扫打赏