js之json对象简单操作
1.声明json对象
var idCard = {"no":"920766616","nation":"汉"};
var person = {"name":"张三","age":23,"isStu":true,"id":idCard};
2.获取对象属性
console.log("获取age属性的值:" + person.age);
console.log("获取age属性的值:" + person["age"]);
打开浏览器,按f12查看控制台console
3.循环获取json对象
for(var i in person){console.log(i + ":" + person[i]);}
var person2 = [{"no":"920766616","nation":"汉"},{"name":"张三","age":23,"isStu":true}];for(var i in person2){for(var j in person2[i]){console.log(person2[i][j]);}}
控制台显示:
4.字符串转换为json格式
var str = '{"no":"920766616","nation":"汉"}';var newStr = JSON.parse(str);console.log(newStr);
控制台显示:
5.json对象定义属性和方法
var jsonStr = {"name" : "fjh",add : function(a,b){return a * b;}};console.log(jsonStr.add(1,2));
控制台显示: