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"}
广告