1.回顾什么是json数据
json数据,就是一个用于表示对象的固定格式的字符串
json数据的格式
var person = JSON.parse('{ "name":"Bill Gates", "age":62, "city":"Seattle"}');
console.log("name: "+person.name);
console.log("age:"+person.age);
console.log("city:"+person.city);
json数据就是字符串,数据为键值对,用单引号引起来就好。可以将json数据转换为js对象,这样更方便后续的操作。
var obj = { "name":"Bill Gates", "today":new Date(), "city":"Seattle"};
var myJSON = JSON.stringify(obj);
console.log(myJSON)
同理:js对象也可以转换为json数据(json字符串)
2.回顾js中的对象,对于我们这种学习java的人来说,习惯性的想先定义类,然后根据类实例化对象。js中对象比java稍微麻烦一些。回顾一些简单的实例:
var person={
name:"zhangSan",
sex:21,
description:function () {
return "hello";
}
};
console.log("name: "+person.name);
console.log("sex:"+person.sex);
console.log(person.description());
定义一个person对象,person对象里面定义了类似于Java的成员变量和成员方法。
运行结果如下:
3.json数据与js对象比较
- 在 JSON 中,键必须是字符串,由双引号包围。js对象不用。
- 在 JSON 中,值必须是以下数据类型之一:字符串,数字,对象(JSON 对象),数组,布尔,null。 js对象值还可以是,函数,日期,undefined
4.完整的练习代码:
<script>
//js对象联系
function fun() {
var person = {
name: "zhangSan",
sex: 21,
description: function () {
return "hello";
}
};
console.log("name: " + person.name);
console.log("sex:" + person.sex);
console.log(person.description());
}
//json数据转换为js对象
function fun1() {
var person = JSON.parse('{ "name":"Bill Gates", "age":62, "city":"Seattle"}');
console.log("name: " + person.name);
console.log("age:" + person.age);
console.log("city:" + person.city);
}
//js对象转换为json数据
function fun2() {
var obj = {"name": "Bill Gates", "today": new Date(), "city": "Seattle"};
var myJSON = JSON.stringify(obj);
console.log(myJSON)
}
//js数组转换为json数据
function fun3() {
var persons = new Array();
persons[0] = {
name: "zhangSan",
sex: 21,
description: function () {
return "hello";
}
};
persons[1] = {
name: "lisi",
sex: 20,
description: function () {
return "word";
}
};
console.log(JSON.stringify(persons));
}
//json数组转换为js对象
function fun4() {
var json = '[{"name":"zhangSan","sex":21},{"name":"lisi","sex":20}]';
var persons = JSON.parse(json);
console.log(persons[0].name);
console.log(persons[1].name);
}
</script>