Home >Web Front-end >JS Tutorial >Summary of methods for parsing Json strings

Summary of methods for parsing Json strings

php中世界最好的语言
php中世界最好的语言Original
2018-05-14 14:11:411624browse

This time I will bring you a summary of the method of parsing JsonString, and what are the notes for parsing 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:

Summary of how to use watch in Vue

How to use the V-bind instruction in VueJs

The above is the detailed content of Summary of methods for parsing Json strings. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn