在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>
效果图:


