在JSON中,有两种结构:对象和数组。
1.对象
一个对象以“{”开始,“}”结束。每个“key”后跟一“:”,“‘key/value’ 对”之间运用 “,”分隔。
packJson = {"name":"caibaojian.com", "password":"111"}
2.数组
packJson = [{"name":"caibaojian.com", "password":"111"}, {"name":"tony", "password":"111"}];
数组是值的有序集合。一个数组以“[”开始,“]”结束。值之间运用 “,”分隔。
JSON对象和JSON字符串的转换
在数据传输流程中,json是以文本,即字符串的形式传递的,而js操作的是JSON对象,所以,JSON对象和JSON字符串之间的相互转换是关键。例如:
JSON字符串:
var jsonStr = '{"name":"caibaojian", "password":"1111"}';
JSON对象:
var jsonObj = {"name":"caibaojian.com", "password":"1111"};
1、String转换为Json对象
var jsonObj = eval('(' + jsonStr + ')');
2.Json对象转换为String字符串
var jsonStr = jsonObj.toJSONString();
jQuery遍历json对象
grep
<script type='text/javascript' src="/jquery.js"></script> <script type="text/javascript"> $().ready( function(){ var array = [1,2,3,4,5,6,7,8,9]; var filterarray = $.grep(array,function(value){ return value > 5;//筛选出大于5的 }); for(var i=0;i<filterarray.length;i++){ alert(filterarray[i]); } for (key in filterarray){ alert(filterarray[key]); } } ); </script>
each
<script type='text/javascript' src="/jquery.js"></script> <script type="text/javascript"> $().ready( function(){ var anObject = {one:1,two:2,three:3};//对json数组each $.each(anObject,function(name,value) { alert(name); alert(value); }); var anArray = ['one','two','three']; $.each(anArray,function(n,value){ alert(n); alert(value); } ); } ); </script>
inArray
<script type='text/javascript' src="/jquery.js"></script> <script type="text/javascript"> $().ready( function(){ var anArray = ['one','two','three']; var index = $.inArray('two',anArray); alert(index);//返回该值在数组中的键值,返回1 alert(anArray[index]);//value is two } ); </script>
map
<script type='text/javascript' src="/jquery.js"></script> <script type="text/javascript"> $().ready( function(){ var strings = ['0','1','2','3','4','S','6']; var values = $.map(strings,function(value){ var result = new Number(value); return isNaN(result) ? null:result;//isNaN:is Not a Number的缩写 } ); for (key in values) { alert(values[key]); } } ); </script>
原生js遍历json对象
遍历json对象:
无规律:
<script> var json = [{dd:'SB',AA:'东东',re1:123},{cccc:'dd',lk:'1qw'}]; for(var i=0,l=json.length;i<l;i++){ for(var key in json[i]){ alert(key+':'+json[i][key]); } } </script>
有规律:
packJson = [ {"name":"nikita", "password":"1111"}, {"name":"tony", "password":"2222"} ]; for(var p in packJson){//遍历json数组时,这么写p为索引,0,1 alert(packJson[p].name + " " + packJson[p].password); }
也可以用这个:
for(var i = 0; i < packJson.length; i++){ alert(packJson[i].name + " " + packJson[i].password); }
遍历json对象
myJson = {"name":"caibaojian", "password":"1111"}; for(var p in myJson){//遍历json对象的每个key/value对,p为key alert(p + " " + myJson[p]); }
有如下 json对象: var obj ={"name":"冯娟","password":"123456","department":"技术部","sex":"女","old":30}; 遍历方法: for(var p in obj){ str = str+obj[p]+’,'; return str; }