How to convert javascript object to json

青灯夜游
Release: 2023-01-03 09:31:52
Original
8373 people have browsed it

In javascript, you can use the "JSON.stringify()" method to convert objects into json, with the syntax format "JSON.stringify(value)"; this method is used to convert JavaScript values into JSON strings , which returns a string containing JSON text.

How to convert javascript object to json

The operating environment of this tutorial: Windows 7 system, ECMAScript version 5, Dell G3 computer.

The common use of JSON is to exchange data with web servers. When sending data to the web server, the data must be a string. Convert JavaScript objects to strings via JSON.stringify().

Example:

var json = {"name":"iphone","price":666}; //创建对象; var jsonStr = JSON.stringify(json); //转为JSON字符串 console.log(jsonStr);
Copy after login

Output:

How to convert javascript object to json

[Recommended learning:js basics Tutorial

JSON.stringify() method introduction

The JSON.stringify() method is used to convert JavaScript values into JSON strings.

Syntax

JSON.stringify(value[, replacer[, space]])
Copy after login

Parameter description:

  • value:

    Required, the JavaScript value to be converted (usually an object or array ).

  • replacer:

    Optional. The function or array used to convert the result.

    If replacer is a function, JSON.stringify will call the function, passing in the key and value of each member. Use the return value instead of the original value. If this function returns undefined, the member is excluded. The key of the root object is an empty string: "".

    If replacer is an array, only members with key values in the array are converted. Members are converted in the same order as the keys in the array.

  • #space:

    Optional, the text adds indentation, spaces and newlines. If space is a number, the return value text is indented at each level specified number of spaces. If space is greater than 10, the text is indented by 10 spaces. Space can also use non-digits, such as: \t.

Return value: Returns a string containing JSON text.

For more programming related knowledge, please visit:Programming Video! !

The above is the detailed content of How to convert javascript object to json. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!