In javascript, you can use the "JSON.stringify()" method to convert an object into a string, which can convert a JavaScript value (usually an object or array) into a JSON string, with the syntax format " JSON.stringify(obj)".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Convert objects to strings in javascript
const obj = { id: 0, name: '张三', age: 12 } const objToStr = JSON.stringify(obj) console.log('obj:', obj) console.log('objToStr:', objToStr)
Output:
JSON.stringify( ) Method
JSON.stringify() method is used to convert a JavaScript value to a JSON string. The syntax is as follows:
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.
Supplement: Convert json string to object
const str = '{"id":0,"name":"张三","age":12}' const strToObj = JSON.parse(str) console.log('str:', str) console.log('strToObj:', strToObj)
Programming Video! !
The above is the detailed content of How to convert object to string in javascript. For more information, please follow other related articles on the PHP Chinese website!