◎筱米加步枪◎.Blog

Happy coding

JavaScript对Json的增删改属性

筱米加步枪 posted @ 2010年10月09日 00:28 in [ 前端技术 ] with tags javascript json , 16412 阅读

使用JS对Json数据的处理,项目遇到需要对Json数据进行相关操作,比如增删改操作,本以为会比较难,网上搜索下,发现还是比较简单的,贴一段代码:

<script type="text/javascript">
		var json = {
			"age":24,
			"name":"cst"
		};
		//修改Json中的age值,因为Json中存在age属性
		json["age"] = 30;
		alert(json.age); //30

		//增加Json中的sex值,因为Json中不存在sex属性
		json["sex"] = "M";
		alert(json.sex); //M

		<!-- 遍历Json中的数据 -->
		for(var key in json){
			try{
				var value = eval("json['" +  key +"']");
				alert(key+"_"+value);
			}catch(e){}
		}

		//删除Json数据中的age属性
		delete json["age"];
		alert(json.age); //undefined

	</script>

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter