JSON学习笔记(2):JavaScript对象与JSON对象的区别

JavaScript 不接受包含特殊字符、连字符或字符串的键。

JSON 对象作为一个包含字符串键的关联数组来处理。

JavaScript 对象可在内部携带函数,而JSON 对象则无法携带任何函数。

下列示例设置了一个属性getFullName , 其中包含了一个函数并在被调用时显示名称John Doe 。

{
"studentid" : 101,
"firstname" : "John",
"lastname" : "Doe",
"isStudent" : true,
"classes" : [
"Business Research",
"Economics",
"Finance"
],
"getFullName" : function(){
alert(`${this.firstname} ${this.lastname}`);
}
}

字符串插值特性是一个新的ES 特性, 可以在表达式"`${}`"中编写变量和函数时使用,该表达式只适用于波浪引号,而不适用于其他类型的引号。

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
let complexJson = {
"studentid" : 101,
"firstname" : "John",
"lastname" : "Doe",
"isStudent" : true,
"scores" : [40, 50],
"courses" : {
"major" : "Finance",
"minor" : "Marketing"
}
};
alert(complexJson.studentid); //101
alert(complexJson.firstname); //John
alert(complexJson.isStudent); //true
alert(complexJson.scores[1]); //50
alert(complexJson.courses.major); //Finance
</script>
</head>
<body>
<h2>Complex Data in JSON</h2>
<p>This is a test program to load complex json data into a variable</p>
</body>
</html>

二者间最大的差别在于, JavaScript 对象并不是一种数据交换格式,而JSON的唯一的目的即用作一种数据交换格式。

猜你喜欢

转载自www.cnblogs.com/techlove/p/12944744.html