// 示例代码:使用 JSON.stringify 方法将 JavaScript 对象转换为 JSON 字符串
const person = {
name: "Alice",
age: 25,
isStudent: false,
courses: ["Math", "Science"],
address: {
city: "Beijing",
country: "China"
}
};
// 将对象转换为 JSON 字符串
const jsonString = JSON.stringify(person);
console.log(jsonString);
// 输出: {"name":"Alice","age":25,"isStudent":false,"courses":["Math","Science"],"address":{"city":"Beijing","country":"China"}}
// 可以传递第二个参数来指定要序列化的属性或修改输出格式
const jsonStringWithReplacer = JSON.stringify(person, ["name", "age"]);
console.log(jsonStringWithReplacer);
// 输出: {"name":"Alice","age":25}
// 可以传递第三个参数来美化输出的 JSON 字符串
const prettyJsonString = JSON.stringify(person, null, 2);
console.log(prettyJsonString);
// 输出:
// {
// "name": "Alice",
// "age": 25,
// "isStudent": false,
// "courses": [
// "Math",
// "Science"
// ],
// "address": {
// "city": "Beijing",
// "country": "China"
// }
// }
上一篇:js mouseover
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站