JSON 数据转字符串全攻略:从 JSON.stringify() 到实际应用
在 JavaScript 开发中,我们经常需要处理数据,JavaScript 对象 (Object) 和 JSON (JavaScript Object Notation) 字符串是两种最常见的数据表现形式,前者是内存中的数据结构,后者是用于网络传输或存储的文本格式,将 JavaScript 对象或值转换为 JSON 字符串是一个核心且高频的操作,本文将探讨如何使用 JSON.stringify() 方法,并揭示其背后的原理、常见用法以及一些实用技巧。
核心方法:JSON.stringify()
在 JavaScript 中,将一个值转换为 JSON 字符串最标准、最直接的方法就是使用全局对象 JSON 上的 stringify() 方法。
语法:
JSON.stringify(value, replacer, space)
它接受三个参数,其中第一个是必需的,后两个是可选的。
基本用法:转换简单值
让我们从最简单的例子开始,看看 JSON.stringify 如何处理不同类型的数据。
转换对象
这是最常见的用法,它会将一个 JavaScript 对象转换成一个 JSON 格式的字符串。
const user = {
id: 101,
name: "张三",
isActive: true,
roles: ["admin", "editor"]
};
const jsonString = JSON.stringify(user);
console.log(jsonString);
// 输出: {"id":101,"name":"张三","isActive":true,"roles":["admin","editor"]}
注意:
- JSON 字符串中的键名必须被双引号包裹,这与 JavaScript 对象字面量语法不同。
- 函数、
undefined、Symbol类型的值在转换过程中会被忽略。
const objWithSpecialValues = {
a: 1,
b: undefined,
c: function() { console.log("hello"); },
d: Symbol('sym')
};
console.log(JSON.stringify(objWithSpecialValues));
// 输出: {"a":1}
// b, c, d 都被忽略了
转换数组
数组也能被顺利转换,其结构会保留。
const numbers = [1, 2, "three", null, false]; const jsonArrayString = JSON.stringify(numbers); console.log(jsonArrayString); // 输出: [1,2,"three",null,false]
转换简单类型
- 数字、布尔值、字符串、null:会被转换为它们对应的 JSON 格式表示。
undefined:会被转换为null。- 函数:会被转换为
undefined。
console.log(JSON.stringify(42)); // 输出: 42
console.log(JSON.stringify("hello")); // 输出: "hello"
console.log(JSON.stringify(true)); // 输出: true
console.log(JSON.stringify(null)); // 输出: null
console.log(JSON.stringify(undefined)); // 输出: null
进阶用法:replacer 和 space 参数
JSON.stringify 的真正强大之处在于它的两个可选参数。
replacer 参数:过滤和转换数据
replacer 可以是一个函数或一个数组,用于控制哪些属性应该被序列化,以及如何序列化它们。
a) replacer 作为数组
如果你只想序列化对象中的特定属性,可以将这些属性的键名组成一个数组。
const user = {
id: 101,
name: "张三",
password: "123456", // 敏感信息,我们不希望它出现在 JSON 中
email: "zhangsan@example.com"
};
// 只保留 name 和 email
const safeJsonString = JSON.stringify(user, ['name', 'email']);
console.log(safeJsonString);
// 输出: {"name":"张三","email":"zhangsan@example.com"}
b) replacer 作为函数
如果你需要对每个属性的值进行自定义处理,可以使用函数,这个函数会在序列化过程中被调用,接收两个参数:key (属性名) 和 value (属性值),函数的返回值将作为该属性在 JSON 字符串中的最终值。
- 如果返回一个非
undefined的值,则该值被序列化。 - 如果返回
undefined,则该属性会被跳过。
const product = {
id: 'p-001',
price: 99.99,
currency: 'CNY'
};
// 将价格四舍五入并添加货币符号
const formattedJsonString = JSON.stringify(product, (key, value) => {
if (key === 'price') {
return `¥${Math.round(value)}`;
}
return value; // 其他属性保持原样
});
console.log(formattedJsonString);
// 输出: {"id":"p-001","price":100,"currency":"CNY"}
space 参数:美化输出
space 参数用于控制输出字符串的缩进和格式,使其更易于人类阅读,它可以是:
- 一个数字 (1-10):表示使用相应数量的空格进行缩进。
- 一个字符串 (如
'\t'或 :使用该字符串作为缩进符。
这在调试或生成配置文件时非常有用。
const data = {
user: "李四",
details: {
age: 30,
hobbies: ["reading", "coding"]
}
};
// 使用 2 个空格缩进
const prettyString1 = JSON.stringify(data, null, 2);
console.log(prettyString1);
/*
输出:
{
"user": "李四",
"details": {
"age": 30,
"hobbies": [
"reading",
"coding"
]
}
}
*/
// 使用制表符缩进
const prettyString2 = JSON.stringify(data, null, '\t');
console.log(prettyString2);
/*
输出:
{
"user": "李四",
"details": {
"age": 30,
"hobbies": [
"reading",
"coding"
]
}
}
*/
实际应用场景
理解了 JSON.stringify 的用法后,我们来看看它在实际开发中是如何应用的。
-
API 数据请求:在与后端服务器进行数据交互时(如使用
fetch或axios),你需要将 JavaScript 对象或数组通过POST请求发送给服务器,这时,JSON.stringify就是必需的步骤。const userData = { username: 'user123', token: 'abc123xyz' }; fetch('https://api.example.com/login', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(userData) // 将对象转为 JSON 字符串作为请求体 }); -
数据存储:浏览器的
localStorage或sessionStorage只能存储字符串,如果你想把一个复杂对象保存起来,必须先用JSON.stringify将其序列化,读取时再用JSON.parse反序列化。const mySettings = { theme: 'dark', notifications: true }; // 保存 localStorage.setItem('settings', JSON.stringify(mySettings)); // 读取 const storedSettings = JSON.parse(localStorage.getItem('settings')); console.log(storedSettings.theme); // 输出: dark -
日志记录与调试:在
console.log一个复杂对象时,浏览器控制台可能不会展示其完整内容,将其先用JSON.stringify转换,可以确保你看到的是所有属性的完整、可复现的字符串表示。const complexObj = { /* ...一个非常复杂的对象... */ }; console.log('Debugging object:', JSON.stringify(complexObj, null, 2));
重要注意事项
-
循环引用:如果一个对象或其子对象引用了自身,
JSON.stringify会直接抛出TypeError。const obj = {}; obj.a = obj; // obj.a 指向了 obj 自身 // 这会报错: Uncaught TypeError: Converting circular structure to JSON JSON.stringify(obj);解决方案是使用库(如 flatted)或手动处理循环引用。
-
对象原型:
JSON.stringify不会包含对象的原型链上的属性,它只处理对象自身的、可枚举的属性。
JSON.stringify() 是 JavaScript 开发者工具箱中一个不可或缺的工具,它不仅是将 JavaScript 值转换为 JSON 字符串的桥梁,更是实现数据持久化、网络通信和调试的关键,通过其基本用法以及 replacer 和 space 参数的进阶技巧,你可以更灵活、更安全地处理数据,从而构建出



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