前端获取JSON数据后的转化全解析:从基础到高级应用
在Web开发中,JSON(JavaScript Object Notation)已成为前后端数据交换的主流格式,前端获取JSON数据后,往往需要根据业务需求进行转化处理,才能适配页面渲染、数据计算或后续操作,本文将从基础解析到高级转化技巧,全面介绍前端获取JSON数据后的转化方法,帮助开发者高效处理数据。
基础解析:将JSON字符串转为JavaScript对象
前端获取的JSON数据通常以字符串形式存在(如AJAX请求响应、API返回的文本数据),需先通过JSON.parse()方法将其转换为JavaScript对象(或数组),才能进行后续操作。
核心方法:JSON.parse()
JSON.parse()是JavaScript内置方法,用于将JSON格式的字符串解析为对应的JS对象/数组。
语法:JSON.parse(text[, reviver])
text:必需,要解析的JSON字符串。reviver:可选,转换函数,可在解析过程中对每个键值对进行预处理。
示例:
// 假设从API获取的JSON字符串
const jsonString = '{"name":"张三","age":25,"hobbies":["阅读","游泳"]}';
// 解析为JS对象
const obj = JSON.parse(jsonString);
console.log(obj.name); // 输出:张三
console.log(obj.hobbies[0]); // 输出:阅读
// 解析JSON数组
const jsonArrayString = '[{"id":1,"title":"文章1"},{"id":2,"title":"文章2"}]';
const arr = JSON.parse(jsonArrayString);
console.log(arr[0].title); // 输出:文章1
常见错误处理
若JSON字符串格式不正确(如单引号、尾随逗号),JSON.parse()会抛出SyntaxError,需结合try-catch处理:
const invalidJson = '{"name":"李四","age":30,}'; // 尾随逗号,格式错误
try {
const obj = JSON.parse(invalidJson);
console.log(obj);
} catch (error) {
console.error("JSON解析失败:", error.message); // 输出:JSON解析失败: Unexpected token }
}
数据转化:从对象到JSON字符串的序列化
当前端需要将JS对象/数组传递给后端(如POST请求),或存储到本地存储(localStorage)时,需通过JSON.stringify()将其序列化为JSON字符串。
核心方法:JSON.stringify()
JSON.stringify()将JS对象/数组转换为JSON格式字符串。
语法:JSON.stringify(value[, replacer[, space]])
value:必需,要转换的JS对象/数组。replacer:可选,过滤函数或数组,用于控制哪些属性被序列化。space:可选,缩进空格数,用于格式化输出(便于调试)。
示例:
const user = {
name: "王五",
age: 28,
hobbies: ["编程","旅行"],
isAdmin: false
};
// 序列化为JSON字符串
const jsonString = JSON.stringify(user);
console.log(jsonString);
// 输出:{"name":"王五","age":28,"hobbies":["编程","旅行"],"isAdmin":false}
// 格式化输出(带缩进)
const formattedJson = JSON.stringify(user, null, 2);
console.log(formattedJson);
/* 输出:
{
"name": "王五",
"age": 28,
"hobbies": [
"编程",
"旅行"
],
"isAdmin": false
}
*/
高级用法:replacer参数
-
过滤属性:通过数组指定需要序列化的属性名:
const user = { id: 1, name: "赵六", password: "123456" }; // 仅序列化id和name,过滤password const filteredJson = JSON.stringify(user, ["id", "name"]); console.log(filteredJson); // 输出:{"id":1,"name":"赵六"} -
自定义转换逻辑:通过函数处理每个键值对:
const data = { score: 85, level: "A", details: { math: 90, english: 80 } }; const customJson = JSON.stringify(data, (key, value) => { // 将level转为小写,其他属性不变 return key === "level" ? value.toLowerCase() : value; }); console.log(customJson); // 输出:{"score":85,"level":"a","details":{"math":90,"english":80}}
复杂数据转化:嵌套结构、日期与特殊类型处理
实际业务中,JSON数据常包含嵌套对象、数组、日期等复杂类型,需针对性处理。
嵌套对象/数组的转化
多层嵌套结构可直接通过JSON.parse()/JSON.stringify()处理,但需注意数据完整性:
const nestedJson = '{"user":{"info":{"name":"钱七","contact":{"email":"qianqi@example.com"}}}}';
const nestedObj = JSON.parse(nestedJson);
console.log(nestedObj.user.info.contact.email); // 输出:qianqi@example.com
日期类型的处理
JSON本身不支持日期类型,JSON.stringify()会将日期转为字符串(如"2024-05-20T12:00:00.000Z"),需手动转换:
方法1:自定义replacer序列化日期
const data = { id: 1, createdAt: new Date("2024-05-20") };
const jsonWithDate = JSON.stringify(data, (key, value) => {
return value instanceof Date ? value.toISOString() : value;
});
console.log(jsonWithDate); // 输出:{"id":1,"createdAt":"2024-05-20T00:00:00.000Z"}
方法2:解析时还原日期
const jsonWithDateString = '{"id":1,"createdAt":"2024-05-20T00:00:00.000Z"}';
const objWithDate = JSON.parse(jsonWithDateString, (key, value) => {
return key === "createdAt" ? new Date(value) : value;
});
console.log(objWithDate.createdAt instanceof Date); // 输出:true
console.log(objWithDate createdAt.toLocaleDateString()); // 输出:2024/5/20
特殊类型(undefined、函数、Symbol)的处理
JSON.stringify()会忽略undefined、函数和Symbol类型的值,需提前处理:
const data = {
name: "孙八",
age: undefined,
sayHi: function() { console.log("hi"); },
id: Symbol("id")
};
// 直接序列化会忽略undefined、函数和Symbol
const json1 = JSON.stringify(data); // 输出:{"name":"孙八"}
// 手动处理特殊类型
const json2 = JSON.stringify(data, (key, value) => {
if (value === undefined) return "undefined";
if (typeof value === "function") return "[Function]";
if (typeof value === "symbol") return value.toString();
return value;
});
console.log(json2); // 输出:{"name":"孙八","age":"undefined","sayHi":"[Function]","id":"Symbol(id)"}
实用场景:数据过滤、格式化与合并
数据过滤:提取特定字段
从复杂数据中提取需要的字段,可通过map+解构或reduce实现:
const users = [
{ id: 1, name: "周九", age: 25, city: "北京" },
{ id: 2, name: "吴十", age: 30, city: "上海" }
];
// 提取id和name
const userInfo = users.map(({ id, name }) => ({ id, name }));
console.log(userInfo); // 输出:[{id:1,name:"周九"},{id:2,name:"吴十"}]
数据格式化:统一字段命名或单位
将字段名转为驼峰或下划线,或统一数值单位:
const products = [
{ product_name: "手机", price: 2999, weight: 0.2 },
{ product_name: "笔记本", price: 5999, weight: 1.5 }
];
// 转为驼峰命名,并添加单位
const formattedProducts = products.map(item => ({
name: item.product_name,
priceYuan: `${item.price}元`,
weightKg: `${item.weight}kg`
}));
console.log(formattedProducts);
/* 输出:
[
{ name:


还没有评论,来说两句吧...