Home > Article > Web Front-end > Summary of Json string usage methods
This time I will bring you a summary of how to use JsonString, what are the Notes when using Json string, the following is a practical case, let’s take a look.
The following will introduce three methods of parsing json strings used in daily life
1. First, let’s take a look at what json format string data is. It is very simple, it is a json string. Transformation, adding odd/even numbers to the json to turn it into string data
var str='{"name":"Mike","sex":"女","age":"29"}'; var t2="[{name:'lisi',age:'30'},{name:'wangwu',age:'16'},{name:'tianqi',age:'7'}] ";
2. We use Object.prototype.toString.call() to detect the data type
console.log(Object.prototype.toString.call(str));//[object String] console.log(Object.prototype.toString.call(t2));//[object String]
The first method: evel();
Features: Low security, not recommended, single JSON object is required Add parentheses, JSON array is no longer needed
Example:
var evajson =eval('('+str+')'); var evajsarr = eval(t2);
After conversion, use Object.prototype.toString.call() to detect the converted data type
console.log(Object.prototype.toString.call(evajso))//[object Object] console.log(Object.prototype.toString.call(evajsarr))//[object Array]
Second type: new Function()
Note: The function must have a return, so "return" must be added;
Example:
var fnjson = new Function("return"+str)(); var fnjsonArr = new Function("return"+t2)();
After conversion, use Object.prototype.toString.call() to detect the converted data type
console.log(Object.prototype.toString.call(fnjson ))//[object Object] console.log(Object.prototype.toString.call(fnjsonArr ))//[object Array]
The third method: JSON.parse()
Features: Mainstream, good compatibility, recommended
Example:
var parjson = JSON.parse(str); var parjson = JSON.parse(t2);
Detect the converted data type
console.log(Object.prototype.toString.call(parjson ))//[object Object] console.log(Object.prototype.toString.call(parjson ))//[object Array]
Believe it After reading the case in this article, you have mastered the method. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
Use case analysis of listener in Vue.js
Use ES6 to make a full-screen scrolling plug-in
The above is the detailed content of Summary of Json string usage methods. For more information, please follow other related articles on the PHP Chinese website!