Home>Article>Web Front-end> How to convert javascript object to json
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.
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);
Output:
[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]])
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!