前言
json.stringify()
方法将一个 javascript 对象或值转换为 json 字符串,如果指定了一个 replacer
函数,则可以选择性地替换值,或者指定的 replacer
是数组,则可选择性地仅包含数组指定的属性。
语法如下:
json.stringify(value[, replacer [, space]])
- 第一个参数
value
:将要序列化成 一个 json 字符串的值。 - 第二个参数
replacer
:可选参数,如果该参数是一个函数,则在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理;如果该参数是一个数组,则只有包含在这个数组中的属性名才会被序列化到最终的 json 字符串中;如果该参数为null
或者未提供,则对象所有的属性都会被序列化。 - 第三个参数
space
:可选参数,指定缩进用的空白字符串,用于美化输出(pretty-print
);如果参数是个数字,它代表有多少的空格;上限为10
。该值若小于1
,则意味着没有空格;如果该参数为字符串(当字符串长度超过 10 个字母,取其前 10 个字母),该字符串将被作为空格;如果该参数没有提供(或者为 null),将没有空格。
第二个参数replacer 为数组
是的,json.stringify()
函数可以有第二个参数,它是要在控制台中打印的对象的键数组。下面来看看示例:
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 对象。
第二个参数replacer 为函数
还可以将第二个参数作为函数传递,根据函数中编写的逻辑评估每个键值对。如果返回 undefined
键值对将不会打印。请看下面示例:
const user = { name: "devpoint", age: 35, }; const result = json.stringify(user, (key, value) => typeof value === "string" ? undefined : value ); console.log(result); // {"age":35}
上述代码的输出,可以用来过滤 json 数据的属性值。
第三个参数为 number
第三个参数控制最终字符串中的间距。如果参数是一个数字,则字符串化中的每个级别都将缩进此数量的空格字符。
const user = { name: "devpoint", age: 35, address: { city: "shenzhen", }, }; console.log(json.stringify(user, null, 4));
输出打印的字符串格式如下:
{
"name": "devpoint",
"age": 35,
"address": {
"city": "shenzhen"
}
}
第三个参数为 string
如果第三个参数是一个字符串,它将被用来代替上面显示的空格字符。
const user = { name: "devpoint", age: 35, address: { city: "shenzhen", }, }; console.log(json.stringify(user, null, "|---"));
输出打印的字符串格式如下:
{
|---"name": "devpoint",
|---"age": 35,
|---"address": {
|---|---"city": "shenzhen"
|---}
}
tojson 方法
有一个名为 tojson
的方法,它可以是任何对象的一部分作为其属性。 json.stringify
返回此函数的结果并将其字符串化,而不是将整个对象转换为字符串。
//initialize a user object const user = { name: "devpoint", city: "shenzhen", tojson() { return `姓名:${this.name},所在城市:${this.city}`; }, }; console.log(json.stringify(user)); // "姓名:devpoint,所在城市:shenzhen"
总结
到此这篇关于js json.stringify()使用场景详解的文章就介绍到这了,更多相关json.stringify()使用场景内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论