什么是JSON.stringify()并解释其在javascript中的用法?

JSON.stringify()

如果需要将数据发送到Web服务器,则数据应为字符串。要将对象文字更改为字符串,应使用JSON.stringify()方法。

示例1

<html>
<body>
<p id="demo"></p>
<script>
   var obj = {name:"rekha", age:40, city:"newyork"};
   var myJSON = JSON.stringify(obj);
   document.getElementById("demo").innerHTML = myJSON;
</script>
</body>
</html>

输出结果

{"name":"rekha","age":40,"city":"newyork"}

示例2

<html>
<body>
<p id="demo"></p>
<script>
   var obj = {"name":"ramesh","age":30,"family":
          [{"mother":"geetha","father":"rao"}],"city":"berlin"};
   var myJSON = JSON.stringify(obj);
   document.getElementById("demo").innerHTML = myJSON;
</script>
</body>
</html>

输出结果

{"name":"ramesh","age":30,"family":[{"mother":"geetha","father":"rao"}],"city":"berlin"}