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

WBOY
Release: 2016-05-16 15:50:14
Original
1489 people have browsed it

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

Copy after login

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]

Copy after login

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

var jsontext = JSON.stringify(jsonObject);
 alert(jsontext);
Copy after login

is displayed as follows:

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

Copy after login

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);

Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template