How to convert object to string using javascript
javascript
string
object
In JavaScript, you can use the "JSON.stringify()" method to convert objects into strings, with the syntax "JSON.stringify(object)". The "JSON.stringify()" method is used to convert js values (objects or arrays) into JSON strings and back.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
In javascript, you can use the "JSON.stringify()" method to convert an object into a string.
Instance: Convert object to string
// 对象 var jsonObj = { "CityId":"18", "CityName":"西安2" }; // 对象转换为字符串 var newString = JSON.stringify(jsonObj); console.log(typeof newString); // 输出:string console.log(newString); // 输出:{"CityId":"18","CityName":"西安2"}
Copy after login
Output:
JSON.stringify( ) method is used to convert a JavaScript value to a JSON string and then returns a string containing the JSON text.
Syntax:
JSON.stringify(value[, replacer[, space]])
Copy after login
Parameters:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <p id="demo"></p> <script> var str = {"name":"PHP中文网", "site":"http://www.php.cn"} str_pretty1 = JSON.stringify(str) document.write( "只有一个参数情况:" ); document.write( "<br>" ); document.write("<pre class="brush:php;toolbar:false">" + str_pretty1 + "
Copy after login
" ); str_pretty2 = JSON.stringify(str, null, 4) //使用四个空格缩进 document.write( "使用参数情况:" ); document.write( "
" ); document.write("
" + str_pretty2 + "
Copy after login