Current location - Recipe Complete Network - Complete cookbook of home-style dishes - How to use JSON objects of JavaScript
How to use JSON objects of JavaScript
In JavaScript, JSON objects include two methods: parse () method and stringify () method; These two methods of using JSON objects can realize the conversion between JSON strings and JavaScript objects. The next article will introduce you to the use of JSON objects in JavaScript.

What is JSON in JavaScript?

JSON is a format for storing and transmitting data; Lightweight human-readable data sets that can be accessed in a logical way.

JSON can generate and store data from user input; Data can be transmitted from server to client, from client to server, and from server to server. You can also build and validate data.

Use of JSON objects

JSON.parse () method

The parse () method of a JSON object can accept a JSON string, convert it into a corresponding JavaScript object, and then return this object. Let's look at the basic sentence patterns:

JSON.parse(text [,reviver])text: the string to be parsed as JSON;

Reviver: Optional parameter that specifies how to convert and parse the originally generated value before returning.

Example:

& lt script & gt

Var json = '{ "Student ID": "0 1", "Name": "Xiaohua", "Age": 20}';

var student = JSON . parse(JSON);

//Output All

Console.log (student);

//Single output

Console.log ("Student ID:"+student. Student number);

Console.log ("name:" +student。 Name);

Console.log ("age:"+student. Age);

& lt/script & gt; The running effect is as follows: Let's look at the output.

JSON.stringify () method

The stringify () method of a JSON object can convert JavaScript values into corresponding JSON strings, and then return the JSON strings. Let's look at the basic sentence patterns:

Json.stringify(value [,replacer [,space]])value: Specifies the js value to be converted into a Json string.

Replacer: optional parameter, which can change the number of behaviors in the process of stringing. If the replacer function is specified, it will replace the value; If a replacer array is specified, it contains only the specified properties.

Space: optional parameter, String or Number object, used to insert spaces in the output JSON string for easy reading.

Example: Convert JavaScript string objects and array objects into JSON strings.

//JavaScript string object

Var json = {Student ID: "0 1", name: "Xiaohua", age: 20};

Var student = JSON. stringify(JSON);

Console.log (student);

//JavaScript array object

var arr = [ "php "," mysql "," JavaScript "];

var bc = JSON。 stringify(arr);

console . log(BC); Output:

Summary: