`
jiav_net
  • 浏览: 103827 次
文章分类
社区版块
存档分类
最新评论

JS中的JSON

 
阅读更多

JSON不是一门语言,是一种数据格式。

相比XML,在JS中使用JSON效率更高,更方便。

// 简单值
			var simpleVal = JSON.parse("25");
			//alert(simpleVal); // 25
			//alert(typeof simpleVal);// number
			simpleVal = JSON.parse("25.1");
			//alert(simpleVal); // 25.1
			//alert(typeof simpleVal);// number		
			simpleVal = JSON.parse("\"allei\"");
			//alert(simpleVal); // allei
			//alert(typeof simpleVal);// string
			//simpleVal = JSON.parse("'allei'"); //error. JSON字符串只能使用双引号
			simpleVal = JSON.parse("true");
			//alert(simpleVal); // true
			//alert(typeof simpleVal);// boolean
			simpleVal = JSON.parse("null");
			//alert(simpleVal); // null
			//alert(typeof simpleVal);// object
			//simpleVal = JSON.parse("undefined"); // JSON不支持undefined
			
			// 对象值
			var objVal = JSON.parse("{\"name\":\"allei\", \"age\":22}"); // JSON对象的属性必须用双引号引起来
			//alert(objVal.name + " " + objVal.age); // allei 22
			//alert(typeof objVal);  // object
			
			// 数组值
			var arrVal = JSON.parse("[25,\"allei\", true, null]");
			//alert(arrVal.join('~')); // 25~allei~true~
			//alert(typeof arrVal); // object
			
			// stringify()把JS对象序列化为JSON字符串
			var obj = {name:"allei",
					age:22,
					print: function (){alert(this.name);}
				};
			//obj.print(); //allei
			var jsonStr = JSON.stringify(obj);
			alert(jsonStr); // {"name":"allei","age":22}
			var newObj = JSON.parse(jsonStr);
			alert(newObj.name + " " + newObj.age); // allei 22
			//newObj.print(); // error. 序列化JS对象时会忽略所有函数和原型成员
另外stringify和parse函数都有一些选项参数可以对序列化和反序列化进行定制

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics