How to convert object to string in javascript

青灯夜游
Release: 2023-01-04 09:34:46
Original
13432 people have browsed it

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)".

How to convert object to string in javascript

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)
Copy after login

Output:

How to convert object to string in javascript

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]])
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.

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)
Copy after login

How to convert object to string in javascript

##For more programming related knowledge, please visit:

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!

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!