0
点赞
收藏
分享

微信扫一扫

【JavaScript的ES6语法】6、ES6有关Json新增的特性


上一篇说完了ES6的面向对象,本篇我们来学习ES6针对Json新增的一些特性。

1、JSON对象
使用JSON对象的stringify方法,可以将JSON对象转换为字符串:

<!DOCTYPE html>
<html>
<head>
<title>TEST ES6</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>

<body>
<script type="text/javascript">
let json={"name":"jack","age":28} ;
let str=JSON.stringify(json);
alert(str);
</script>
</body>
</html>

效果:

【JavaScript的ES6语法】6、ES6有关Json新增的特性_JSON.parse


使用JSON对象的方法,可以将字符串转换为JSON对象:

<!DOCTYPE html>
<html>
<head>
<title>TEST ES6</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>

<body>
<script type="text/javascript">
let str='{"name":"jack","age":28}';
let json=JSON.parse(str);
alert("JSON对象:"+json);
</script>
</body>
</html>

【JavaScript的ES6语法】6、ES6有关Json新增的特性_JSON语法_02


可以看到输出了一个Object对象,转换JSON对象成功。

这里要注意,我们要了解json的标椎写法,必须遵循以下标准:

(1)所有的名字都必须用引号包起来
(2)只能用双引号

如:

{name:'jack',age:28} 是

{"name":"jack","age":28}  是

只要不遵循上面规则的,parse方法就不能转换成标准的JSON对象。

2、JSON简写
假设我们需要拼接多个参数形成一个JSON,一般如以下写法:

<!DOCTYPE html>
<html>
<head>
<title>TEST ES6</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>

<body>
<script type="text/javascript">
let a=1;let b=2;
let json={"a":a,"b":b};
alert(JSON.stringify(json));
</script>
</body>
</html>

效果:

【JavaScript的ES6语法】6、ES6有关Json新增的特性_stringify_03

但是在新版的ES6中,名字和值一样的时候,可以只写值:

<script type="text/javascript">
let a=1;let b=2;
let json={a,b};
alert(JSON.stringify(json));
</script>

会简洁很多。

json中如果包含函数,一般的写法如下:

<script type="text/javascript">
let json={
"a":1,
show: function(){
alert(this.a);
}
}
json.show();
</script>

效果:

【JavaScript的ES6语法】6、ES6有关Json新增的特性_JSON对象_04


在ES6中,我们可以将“: function”去除:

<script type="text/javascript">
let json={
"a":1,
show(){
alert(this.a);
}
}
json.show();
</script>

json相关的特性就讲到这里,下一篇我们来讲解Promise。

参考:深入解读ES6系列视频教程(kaikeba.com提供)

举报

相关推荐

0 条评论