JSON(javascript Object Notation) 是一種輕量級的數據交換格式,採用徹底獨立於語言的文本格式,是理想的數據交換格式。同時,JSON是 JavaScript 原生格式,這意味着在 JavaScript 中處理 JSON數據不需要任何特殊的 API 或工具包。javascript
在JSON中,有兩種結構:對象和數組。java
1.對象jquery
一個對象以「{」開始,「}」結束。每一個「key」後跟一「:」,「‘key/value’ 對」之間運用 「,」分隔。json
packJson = {"name":"caibaojian.com", "password":"111"}數組
2.數組工具
packJson = [{"name":"caibaojian.com", "password":"111"}, {"name":"tony", "password":"111"}];spa
數組是值的有序集合。一個數組以「[」開始,「]」結束。值之間運用 「,」分隔。對象
在數據傳輸流程中,json是以文本,即字符串的形式傳遞的,而JS操做的是JSON對象,因此,JSON對象和JSON字符串之間的相互轉換是關鍵。例如:索引
JSON字符串:three
var jsonStr = '{"name":"caibaojian", "password":"1111"}';
JSON對象:
var jsonObj = {"name":"caibaojian.com", "password":"1111"};
一、String轉換爲Json對象
var jsonObj = eval('(' + jsonStr + ')');
2.Json對象轉換爲String字符串
var jsonStr = jsonObj.toJSONString();
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>
遍歷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; }