Knowledge JSON.stringify new solution ------

JSON.stringify (value [, replacer] [, space]): After two parameter is optional, discussed next

 Converting the value JavaScript JavaScript Object Notation (Json) string. Note: The value of the method is not converted to a string, converts only arrays of various types and values.

 Parameter Description: https://www.cnblogs.com/xiaoniuzai/p/6419124.html

 value

  •   essential. JavaScript value to be converted (to support all data types, but typically pass an object or array). And not allow circular references.

   

 space

  •   Optional. Adding JSON return value to indent text, spaces and line breaks to make it easier to read.
  •   If you omit the space, the return value will be generated text, without any extra spaces.
  •   If space is a number, the return value of a specified number of spaces to indent text in each level. If the space is larger than 10, the text is indented 10 spaces.
  •   If space is a non-empty string (e.g., "\ t"), the value of the text characters in the string in each indent level returns.
  •   If the space is greater than the string length of 10 characters, the first 10 characters is used.

replacer

  • Special attention , when the value of the parameter is an array, the array {} indicates that the object in the key, the only key contained in the array will be returned, provided that when the first parameter is an object, when the array parameter is ignored ~~~
  • The second parameter is very interesting, can function as a filter, it may be an array.
  • When the array is a sequence of each attribute values ​​are subjected to conversion and processing of the function
  • When the array is the first parameter only attribute name contained in the array will be serialized into the final JSON string.

 

\ t: represents an empty four characters, also known as indentation, it is equivalent to pressing the Tab key

var arr = ["hunter","children", "age"];

ret =JSON.stringify(arr, null, '\t');  第三个参数表示跳到下一个制表位,空格数为tab的位数(4)
ret =JSON.stringify(arr, array1, 3);  第三个参数表示每行空的字符位数(可以是1~n数字 n> 10按十个字符,即最大为10个字符)



打印结果:
"[
   "hunter",
   "children",
   "age"
]"

针对replacer参数为数组的情况:注意前面是数组该参数为数组会被忽略掉~
var data = {
  name:"niuzai",
  info:{
    age:18,
    sex:"male"
  }
};
================================================
JSON.stringify(data,['name','info','age'],'\t')
"{
	"name": "niuzai",
	"info": {
		"age": 18    // 这里数组未含有sex则返回时会忽略掉它~~~~~~~
	}
}"



注意:
字符串值以引号开始和结束。 所有 Unicode字符可括在引号中,
但必须使用反斜杠进行转义的字符除外。 以下字符的前面必须是反斜杠:
  引号 (")      \"
  反斜杠 (\)    \\
  退格键 (b)    \b
  换页符 (f)    \f
  换行符 (n)    \n
  回车符 (r)    \r
  水平制表符 (t)  \t
  四个十六进制数字(uhhhh)

 

发布了163 篇原创文章 · 获赞 31 · 访问量 4万+

Guess you like

Origin blog.csdn.net/COCOLI_BK/article/details/103395610