The method of converting objects and strings to each other in js

When I was studying today, I encountered the two methods of json_stringify and json_parse. I wondered if there was any similarity between them, so I
searched online. Next, let’s find out together.
Let’s look at the following code first .

			var obj = {
				'name':'lala',
				'age':19,
				'sex':'nan'
			}
			var arr1 = ['stuid','classid',51];
			var arr2 = ['name','age',11];
			//	一个参数时
			console.log(JSON.stringify(obj));
			//	两个参数时    第二个参数为数组,可以看到只显示了name和age,因为sex属性在数组arr2里没有,所以没显示
			var doublearr = JSON.stringify(obj,arr2);
			console.log(doublearr);
			//	两个参数时    二个参数都为数组,只会显示第一个
			console.log(JSON.stringify(arr1,arr2));
			//	两个参数时    第二个参数为函数,返回json类型格式的字符串
			var doubargment = JSON.stringify(obj,function (key,value) {
				return value;
			});
			console.log(doubargment);
			//	三个参数时    第三个参数为分隔符,可以看到都是以gbk开头的
			console.log(JSON.stringify(obj,function (key,value) {
				return value;
			},'gbk'));

The running effect is as follows
insert image description here
Let's take a look at the usage of json_parse

			var str = '{"name":"lala","age":13,"sex":{"fist":"nan","two":"nv"}}';
			var obj = JSON.parse(str);
			console.log(typeof obj)
			console.log(obj);

The operation effect is as follows
insert image description here
, we can see that our string str has been converted into an object. From the above two cases, we can find that the function of json_stringify is to convert the object into a string of json type format, while json_parse is to convert the characters of js type format string to object

Note: json_parse must be in json format to convert, otherwise it will report an error, pure numbers and string 'null' will not report an error

Alright, it's time for our summary today

  1. json_stringify ---- Convert an object to a string in json format
    1. Syntax: JSON.stringify(value object[, replacer function/array] [, space delimiter])
    2. If both the first parameter and the second parameter are arrays, only the first one will be displayed
    3. Object + array display common, object attribute == array value
    4. If the delimiter is a number, then it defines how many characters to indent. Of course, if it is greater than 10, the maximum value is 10
  2. json_parse ---- Convert a string in json format to a json object
    1. Syntax: json_parse(json-str)

This is the end of today's study, goodbye~

Guess you like

Origin blog.csdn.net/Smallwhitestrive/article/details/120927873
Recommended