Home >Web Front-end >JS Tutorial >Detailed explanation of the difference between JSON.parse() and JSON.stringify() and how to use it

Detailed explanation of the difference between JSON.parse() and JSON.stringify() and how to use it

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

This time I will give you a detailed explanation of the difference between JSON.parse() and JSON.stringify() and how to use it. What are the precautions when using JSON.parse() and JSON.stringify()? , the following is a practical case, let’s take a look.

1.parse is used to parse a json object from a string. For example

var str='{"name":"cpf","age":"23"}'

Get through JSON.parse(str):

Object: age:"23"
      name:"cpf"
      _proto_:Object

ps: Single quotes are written outside {}, and each attribute must be double quoted, otherwise an exception will be thrown

2.stringify is used to extract data from an object Parse out the string, for example

var a={a:1,b:2}

Obtained through JSON.stringify(a):

"{"a" :1,"b":2}"

JSON.stringify, this function is mainly used to serialize objects. (Or convert the original object into a string, such as a json object):

First define a json object, var jsonObject = { "UserID": "1", "UserName": "xiaozhang" };

Use alert(jsonObject) to pop up and display:

[Object Object]

Then call JSON.stringify to convert the json object into a json string.

var jsontext = JSON.stringify(jsonObject);
 alert(jsontext);

is displayed as follows:

{ "UserID": "1", "UserName": "xiaozhang" }

2. jQuery.parseJSON, converts a JSON string into a JSON object (JSON.parse also parses a json string into a json object), as shown below

First define a JSON string, var c = '{"name":"Mike","sex":"male","age":"29"}'; (Note: write in single quotes Outside {}, each attribute name must be in double quotes, otherwise an exception will be thrown)

Then call jQuery.parseJSON to convert it to a JSON object,

var employeejson=jQuery.parseJSON(c);

when accessed. Use employeejson.name, employeejson.sex, employeejson.age to get the corresponding value

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:

Methods for JS to convert XML and JSON to each other

What are the methods for JS to determine json

The above is the detailed content of Detailed explanation of the difference between JSON.parse() and JSON.stringify() and how to use it. 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