在JavaScript中,可以使用“JSON.stringify()”方法将对象转为字符串。
实例:对象转换为字符串
// 对象 var jsonObj = { "CityId":"18", "CityName":"西安2" }; // 对象转换为字符串 var newString = JSON.stringify(jsonObj); console.log(typeof newString); // 输出:string console.log(newString); // 输出:{"CityId":"18","CityName":"西安2"}
输出:
JSON.stringify() 方法用于将 JavaScript 值转换为 JSON 字符串,然后返回包含 JSON 文本的字符串。
语法:
JSON.stringify(value[, replacer[, space]])
参数:
示例:
<!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>" + str_pretty1 + "</pre>" ); document.write( "<br>" ); str_pretty2 = JSON.stringify(str, null, 4) //使用四个空格缩进 document.write( "使用参数情况:" ); document.write( "<br>" ); document.write("<pre>" + str_pretty2 + "</pre>" ); // pre 用于格式化输出 </script> </body> </html>
效果图:
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)