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

本文介绍了如何使用JSON定义一维和二维数组,并提供了示例代码。一维数组示例展示了如何访问对象属性,而二维数组示例展示了如何遍历嵌套结构。同时提到了服务器返回的JSON内容格式以及如何在JavaScript中创建和赋值JSON格式的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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" }
  ] }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值