JSON.stringify(value[, replacer [, space]])第一个参数 value:将要序列化成 一个 JSON 字符串的值。
第三个参数 space:可选参数,指定缩进用的空白字符串,用于美化输出(pretty-print);如果参数是个数字,它代表有多少的空格;上限为 10。该值若小于 1,则意味着没有空格;如果该参数为字符串(当字符串长度超过 10 个字母,取其前 10 个字母),该字符串将被作为空格;如果该参数没有提供(或者为 null),将没有空格。
// 堆代码 duidaima.com const arrayData = [ { id: "0001", type: "donut", name: "Cake", ppu: 0.55, batters: { batter: [ { id: "1001", type: "Regular" }, { id: "1002", type: "Chocolate" }, { id: "1003", type: "Blueberry" }, { id: "1004", type: "Devil’s Food" }, ], }, topping: [ { id: "5001", type: "None" }, { id: "5002", type: "Glazed" }, { id: "5005", type: "Sugar" }, { id: "5007", type: "Powdered Sugar" }, { id: "5006", type: "Chocolate with Sprinkles" }, { id: "5003", type: "Chocolate" }, { id: "5004", type: "Maple" }, ], }, ]; console.log(JSON.stringify(arrayData, ["name"])); // [{"name":"Cake"}]可以通过在第二个参数中将其作为数组传递仅需要打印的键,而不需要打印整个 JSON 对象。
const user = { name: "DevPoint", age: 35, }; const result = JSON.stringify(user, (key, value) => typeof value === "string" ? undefined : value ); console.log(result); // {"age":35}上述代码的输出,可以用来过滤 JSON 数据的属性值。
const user = { name: "DevPoint", age: 35, address: { city: "Shenzhen", }, }; console.log(JSON.stringify(user, null, 4));输出打印的字符串格式如下:
{ "name": "DevPoint", "age": 35, "address": { "city": "Shenzhen" } }
const user = { name: "DevPoint", age: 35, address: { city: "Shenzhen", }, }; console.log(JSON.stringify(user, null, "|---"));输出打印的字符串格式如下:
{ |---"name": "DevPoint", |---"age": 35, |---"address": { |---|---"city": "Shenzhen" |---} }
//Initialize a User object const user = { name: "DevPoint", city: "Shenzhen", toJSON() { return `姓名:${this.name},所在城市:${this.city}`; }, }; console.log(JSON.stringify(user)); // "姓名:DevPoint,所在城市:Shenzhen"