Home >Web Front-end >JS Tutorial >A brief discussion on JSON.parse() and JSON.stringify()_javascript techniques

A brief discussion on JSON.parse() and JSON.stringify()_javascript techniques

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-16 15:50:141526browse

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

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

Get via 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 parse a string from an object, such as

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

Get via 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: single quotes are written in {} In addition, each attribute name must be enclosed 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 accessing, use employeejson.name, employeejson.sex, employeejson.age to get the corresponding value

The above is the entire content of this article, I hope you all like it.

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