日期:2014-05-16  浏览次数:20568 次

JSON定义和处理 一维和二维数组的格式
JSON定义一维数组:

示例完整代码:

<script>
var UserList = [
{"UserID":11, "Name":{"FirstName":"Truly","LastName":"Zhu"}, "Email":"zhuleipro◎hotmail.com"},
{"UserID":12, "Name":{"FirstName":"Jeffrey","LastName":"Richter"}, "Email":"xxx◎xxx.com"},
{"UserID":13, "Name":{"FirstName":"Scott","LastName":"Gu"}, "Email":"xxx2◎xxx2.com"}
];
alert(UserList[0].Name.FirstName);
</script>
事实上除了使用"."引用属性外,我们还可以使用下面语句:

alert(UserList[0]["Name"]["FirstName"]); 或者 alert(UserList[0].Name["FirstName"]);


JSON定义二维数组:
示例完整代码:
<script type="text/javascript">
//定义sJon为二维数组形式
var sJson={
"rec":[
{"recs":
[
{
"temLink":"00",
"imageLink":"",
"itemPrice":"",
"itemLink":"","
itemName":""
},
{"temLink":"01","imageLink":"","itemPrice":"","itemLink":"","itemName":""}
]
},
{
"recs":
[
{"temLink":"10","imageLink":"","itemPrice":"","itemLink":"","itemName":""},
{"temLink":"11","imageLink":"","itemPrice":"","itemLink":"","itemName":""}
]
}
]
};
alert(sJson.rec[0].recs[0].temLink);

</script>

另:
服务器返回客户端的Json内容格式
["abc",1234,'def','ab']

{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }

[{
        id: 1,
        text: 'A leaf Node',
        leaf: true
    },{
        id: 2,
        text: 'A folder Node',
        children: [{
            id: 3,
            text: 'A child Node',
            leaf: true
        }]
  }]


另JSON 格式的数据创建:
可以创建一个新的 JavaScript 变量,然后将 JSON 格式的数据字符串直接赋值给它:
  var people = { "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
  { "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },
  { "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
  ],
  "authors": [
  { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
  { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
  { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
  ],
  "musicians": [
  { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
  { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
  ] }