欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JSON简介

程序员文章站 2022-06-17 18:52:30
...
<html>
	<head>
		<title>JSON简介</title>
		<meta charset="UTF-8" />
		<script>
			/**
				JavaScript JSON对象
			*/
			var contents = [
				{
				"abbreviation":"JSON"/*abbreviation:简称*/
				,"autonym":"JavaScript Object Notatton"/*autonym:全称*/
				,"chinese":"JavaScript 对象表示法"/*chinese:中文意思*/
				,"explain":"JSON是存储和交换文本信息的语法,类似XML。JSON比XML更小、更快、更容易解析。"/*explain:说明*/
				}
			];
			function iterateContents(contents) {
				for(var n = 0; n < contents.length; n++) {
					var content = contents[n];
					document.write(content.abbreviation);document.write('<br/>');
					document.write(content.autonym);document.write('<br/>');
					document.write(content.chinese);document.write('<br/>');
					document.write(content.explain);document.write('<br/>');
				}
			}
			iterateContents(contents);
			document.write('<br/>');
			
			/**
				JavaScript JSON字符串转JSON对象
			*/
			var goodsContentsStr = '[{"name":"水杯","price":"20"},{"name":"抽纸","price":"5"}]';
			var goodsContents = JSON.parse(goodsContentsStr);
			function iterateGoodsContents(goodsContents) {
				document.write(JSON.stringify(goodsContents));//JSON对象转字符串
				document.write('<table>');
				document.write('<tr><th>商品名称</th><th>商品价格</th></tr>');
				for(var n = 0; n < goodsContents.length; n++) {
					var goods = goodsContents[n];
					document.write('<tr>');
					document.write('<td>');
					document.write(goods.name);
					document.write('</td>');
					document.write('<td>');
					document.write(goods.price);
					document.write('</td>');
					document.write('</tr>');
				}
				document.write('</table>');
			}
			iterateGoodsContents(goodsContents);
		</script>
	</head>
	<body>
	</body>
</html>