Home >Web Front-end >JS Tutorial >What are the methods for parsing Json?

What are the methods for parsing Json?

php中世界最好的语言
php中世界最好的语言Original
2018-04-25 09:37:121803browse

This time I will bring you what methods are available for parsing Json, and what are the precautions for parsing Json. The following is a practical case, let's take a look.

In recent projects, there are always interfaces that are being transferred back and forth. I don’t understand them deeply and it is very confusing, so I will briefly organize them for future reference.

[StringConvert to object]

•parse is used to parse a json object from a string , such as
•var str = '{"name":"demo","age":"22"}'

•Result:

•JSON.parse(str)
Object
•age: "22"
•name: "demo"
proto: Object

1.eval('(' str ')');//eval() method dynamically executes the string (possibly a js script), which can easily cause system security issues.

var str='{ "name": "John" }';
var obj = eval('(' + str + ')'); 
alert( obj.name);

2.parseJSON(str)

var str='{ "name": "John" }';
var obj = jQuery.parseJSON(str)
alert("1"+ obj.name);

3.JSON.parse(str)

var str = '{ "name": "mady", "age": "24" }';
var obj = JSON.parse(str);
alert(obj.name);

4.jquery-json extension library download:http://code.google.com/p/jquery-json/

[Convert object to string]

•stringify() is used to parse a string from an object, such as
•var a = {a:1,b:2}

•Result:

•JSON.stringify(a)
•"{"a":1,"b":2}"

You can use toJSONString() or the global method JSON.stringify() Convert JSON object to JSON string.

For example:

var last=obj.toJSONString(); //将JSON对象转化为JSON字符

or

var last=JSON.stringify(obj); //将JSON对象转化为JSON字符
alert(last);

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of JSONP principles and case analysis

Detailed explanation of the differences between ajax and jsonp and json usage steps

The above is the detailed content of What are the methods for parsing Json?. 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