Home >Web Front-end >JS Tutorial >How to convert JavaScript object to json format

How to convert JavaScript object to json format

不言
不言Original
2018-11-17 14:40:1223928browse


JavaScript中要将对象转换为JSON格式字符串,我们需要使用JSON.stringify()方法,下面我们来看具体的内容。

JSON.stringify()语法格式:

JSON.stringify([要转换的对象])

JSON.stringify([要转换的对象],[转换函数])
JSON.stringify([要转换的对象],[转换函数],[空白处理方法])

一个具体实例

代码如下:

创建以下HTML文件

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title></title>
  <script type="text/javascript">
    var obj = {
      name: "饼干",      
      code: "PC-001",      
      price: 360,      
      getInfo: function () {
              return this.name + " = \\" + this.price;
      }
    }    
  function ObjectToJson() {
               var jsontext = JSON.stringify(obj);      
                var elem = document.getElementById("textarea1");
      elem.innerText = jsontext;
    }  
</script>
</head>
<body>
  <div></div>
  <div><textarea id="textarea1" cols=80 rows=20 wrap="off"></textarea></div>
</body>
</html>

说明:

使用以下代码定义对象。

 var obj = {
      name: "饼干",
      code: "PC-001",
      price: 360,
      getInfo: function () {
        return this.name + " = \\" + this.price;
      }
    }

单击该按钮时,将调用以下ObjectToJson()函数。调用JSON.stringify()方法将对象转换为JSON字符串。将要转换的对象作为第一个参数。
转换后的结果将作为JSON.stringify()的返回值返回。在此代码中,结果JSON格式字符串显示在文本区域中。

  function ObjectToJson() {
      var jsontext = JSON.stringify(obj);
      var elem = document.getElementById("textarea1");
      elem.innerText = jsontext;
    }

执行结果:

使用Web浏览器显示上述HTML文件。将显示如下所示的效果:

How to convert JavaScript object to json format

单击“button”按钮。JavaScript对象的信息转换为JSON字符串,并在文本区域中显示为文本字符串。

How to convert JavaScript object to json format

本篇文章到这里就全部结束了,更多有关内容大家可以关注php中文网视频教程栏目观看相关视频!!!


The above is the detailed content of How to convert JavaScript object to json format. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn