JS single-line object string to object

	var strObj0 = '{banana : "pear"}';
	var strObj1 = "{mango : \"strawberry\"}";
	    
	var apple = "a=" + strObj0;
	var peach = "b=" + strObj1;
	
	var grape = eval(apple);
	var durian = eval(peach);
	
	console.log(grape);
	console.log(durian);

When receiving some strange data from the backend, for example, the received data is converted by JSON.stringify or JSON.parse '{banana : "pear"}'or "{mango : \"strawberry\"}"such data, that is, the object wrapped in quotation marks, is output to the console to display a String string, and if we want to use the object in this string, we will not be able to get the corresponding value.

eval()

Splice the front of the string "a=", and then pass in a new string to eval(), for example: console.log(eval("a=" + str)), but the eval() function is generally not recommended, it has many disadvantages, please Baidu separately.

Attach a description of the disadvantages of eval(): eval has security issues, it will execute any code passed to it, never use the eval function when the code string is unknown or comes from an untrusted source.
Definitely don't use eval, any code that uses it will be questioned in terms of how it works, performance and security. If some cases must use eval to work properly, first of all its design will be questioned, this should not be the preferred solution, a better solution without eval should be fully considered and preferred.

Guess you like

Origin blog.csdn.net/Lyxxxxxx777/article/details/123098877