摘要:本文学习了JS处理JSON数据的方法和技巧。
1 简介
JSON是JS的内置对象,提供了处理JSON数据的方法。
JSON对象主要包含两个方法:
JSON.parse()方法将JSON字符串转换为JS对象。
JSON.stringify()方法将JS对象转换为JSON字符串。
2 字符串转对象
基本用法:
js1 2 3 4
| const jsonString = '{"name": "李四", "age": 18}'; const jsonObject = JSON.parse(jsonString); console.log(jsonObject.name); console.log(jsonObject.age);
|
解析数组:
js1 2 3 4 5
| const jsonString = '["苹果", "香蕉", "橙子"]'; const array = JSON.parse(jsonString); console.log(array[0]); console.log(array[1]); console.log(array[2]);
|
解析嵌套对象:
js1 2 3 4 5 6 7 8 9 10 11 12 13 14
| const jsonString = ` { "person": { "name": "李四", "address": { "city": "北京", "street": "人民路" } } } `; const data = JSON.parse(jsonString); console.log(data.person.name); console.log(data.person.address.city);
|
在解析过程中转换值:
js1 2 3 4 5 6 7 8 9 10 11
| const jsonString = '{"name": "李四", "age": 18}'; const data = JSON.parse(jsonString, function(key, value) { if (key === 'age') { return value + '岁'; } return value; }); console.log(jsonObject.name); console.log(jsonObject.age);
|
错误处理:
js1 2 3 4 5 6 7 8 9 10
| function safeParse(jsonString) { try { return JSON.parse(jsonString); } catch (error) { console.error('JSON解析错误:', error.message); return null; } } console.log(safeParse('{"name": "李四"}')); console.log(safeParse('{name: "李四"}'));
|
3 对象转字符串
基本用法:
js1 2 3 4 5 6 7 8
| const person = { name: "李四", age: 18, hobbies: ["读书", "游泳"] }; const jsonString = JSON.stringify(person);
console.log(jsonString);
|
转换规则:
js1 2 3 4 5 6 7 8 9 10 11
| const data = { name: "李四", age: 18, date: new Date(), nullValue: null, nanValue: NaN, undefinedValue: undefined, functionValue: function() {} };
console.log(JSON.stringify(data));
|
转换指定属性:
js1 2 3 4 5 6 7 8
| const person = { name: "李四", age: 18, email: "lisi@example.com" }; const jsonString = JSON.stringify(person, ['name', 'age']);
console.log(jsonString);
|
过滤敏感信息:
js1 2 3 4 5 6 7 8
| const jsonString = JSON.stringify(person, function(key, value) { if (key === 'email') { return value.replace(/@.*$/, '@***'); } return value; });
console.log(jsonString);
|
条