###json数组对象和对象数组
1、Json的简单介绍 vue
从结构上看,全部的数据最终均可以分红三种类型:
第一种类型是scalar(标量),也就是一个单独的string(字符串)或数字(numbers),好比“北京”这个单独的词。 json
第二种类型是sequence(序列),也就是若干个相关的数据按照必定顺序并列在一块儿,又叫作array(数组)或List(列表),好比“浙江,江苏”。 数组
第三种类型是mapping(映射),也就是一个名/值对(Name/value),即数据有一个名称,还有一个与之相对应的值,这又称做hash(散列)或dictionary(字典),好比“首都:北京”。 app
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,它的规则很是简单而且是有趣的: 框架
1) 并列的数据之间用逗号(“,”)分隔。 scala
2) 映射用冒号(“:”)表示。 对象
3) 并列数据的集合(数组)用方括号("[]")表示。 ip
4) 映射的集合(对象)用大括号(“{}”)表示。 字符串
按照这个规则能够做如下理解: string
1.数组用“[]”建立,对象用“{}”建立,而且使用Json基本都是用[]或者{}建立的数组或对象,不然一个普通的字符串是没有意义的;
2.不管是数组仍是对象,之间的元素都用“,”隔开;
3.对象内部,(属性的)名称和值用“:”隔开,而且必需要用“:”隔开,不可单独存在属性名或者值;
4.对象和数组能够互相嵌套,即数组中的一个元素能够是一个对象也能够是一个数组,同理对象中的一个属性的值能够是一个对象也能够是一个数组。
2、实例
下面是后台返回来的json数据,以前遇到一个问题就一直获取不到userStatisticsVos里channel属性里的id和name.
####Json
{
"ok":true,
"c":0,
"m":"success",
"r":{
"userStatisticsVos":[
{
"totalUser":81,
"ipCount":82,
"activeUser":62,
"paidUser":0,
"channel":null,
"newUser":68,
"oldUser":13
},
{
"totalUser":3,
"ipCount":3,
"activeUser":3,
"paidUser":0,
"channel":{
"id":1,
"createTime":1493972249000,
"updateTime":1494052769000,
"name":"test",
"type":1
},
"newUser":3,
"oldUser":0
},
],
}
}
####HTML
`<table class="table table-bordered table-hover text-center tabletList">
<thead>
<tr>
<th class="bgColor">渠道Id</th>
<th class="bgColor">渠道名称</th>
<th class="bgColor">总用户</th>
<th class="bgColor">新增用户</th>
<th class="bgColor">老用户</th>
<th class="bgColor">ip</th>
<th class="bgColor">活跃用户</th>
<th class="bgColor">付费用户</th>
</tr>
</thead>
<tbody>
<tr v-for="x in userStatisticsVos">
<td v-text="x.channel.id"></td>
<td v-text="x.channel.name"></td>
<td v-text="x.totalUser"></td>
<td v-text="x.newUser"></td>
<td v-text="x.oldUser"></td>
<td v-text="x.ipCount"></td>
<td v-text="x.activeUser"></td>
<td v-text="x.paidUser"></td>
</tr>
</tbody>
</table>
`
恩,只是我一开始写的(首先声明下我用的是vue框架,userStatisticsVos已经声明了),可是这样写发现了一个错误,控制台会报错
‘TypeError:Cannot read property 'id' of null
’
意思是说id这个属性没有找到。
后来,是由于后台传给个人channel的值有个是null,因此他是没法获取channel属性里的id属性的,找到了问题的缘由,那解决他就简单了。对给channel加个判断。下面是我修改后的代码: `<table class="table table-bordered table-hover text-center tabletList"> <thead> <tr> <th class="bgColor">渠道Id</th> <th class="bgColor">渠道名称</th> <th class="bgColor">总用户</th> <th class="bgColor">新增用户</th> <th class="bgColor">老用户</th> <th class="bgColor">ip</th> <th class="bgColor">活跃用户</th> <th class="bgColor">付费用户</th> </tr> </thead> <tbody> <tr v-for="x in userStatisticsVos"> <td v-if='!(x.channel === null)' v-text="x.channel.id"></td> <td v-else></td> <td v-if='!(x.channel === null)' v-text="x.channel.name"></td> <td v-else></td> <td v-text="x.totalUser"></td> <td v-text="x.newUser"></td> <td v-text="x.oldUser"></td> <td v-text="x.ipCount"></td> <td v-text="x.activeUser"></td> <td v-text="x.paidUser"></td> </tr> </tbody> </table> `恩,这样就能够获取到channel属性里的id和name的值了。顿时以为自已好笨呐,那么简单的问题,都要想那么久。不行,我要去角落里哭去了。。。。