在鸿蒙Next(HarmonyOS NEXT)中,可以使用 JSON.stringify() 方法结合 console.log() 实现JSON格式化全量打印。以下是具体实现方法:
核心代码:
// 假设有一个JSON对象
let data = {
name: "张三",
age: 25,
address: {
city: "北京",
district: "海淀区"
},
hobbies: ["阅读", "编程", "运动"]
};
// 全量格式化打印
console.log(JSON.stringify(data, null, 2));
参数说明:
- 第一个参数:要转换的JSON对象
- 第二个参数:替换函数(null表示不使用)
- 第三个参数:缩进空格数(推荐2或4)
更完整的示例:
function printJson(obj) {
try {
const formattedJson = JSON.stringify(obj, null, 2);
console.log(formattedJson);
} catch (error) {
console.error("JSON格式化失败:", error);
}
}
// 使用示例
const userInfo = {
id: 1,
profile: {
name: "李四",
age: 30,
tags: ["developer", "harmonyos"]
}
};
printJson(userInfo);
输出效果:
{
"id": 1,
"profile": {
"name": "李四",
"age": 30,
"tags": [
"developer",
"harmonyos"
]
}
}
注意事项:
- 确保对象是可序列化的(不包含函数、循环引用等)
- 对于包含特殊字符的情况,JSON.stringify会自动处理转义
- 在鸿蒙开发中,可以使用console.log在DevEco Studio的Log窗口中查看输出
这种方法适用于所有标准的JSON对象,能够清晰展示完整的数据结构层次。