关于json数组对象和对象数组遇到的一些问题

###json数组对象和对象数组
一、Json的简单介绍

从结构上看,所有的数据最终都可以分成三种类型:

第一种类型是scalar(标量),也就是一个单独的string(字符串)或数字(numbers),比如“北京”这个单独的词。

第二种类型是sequence(序列),也就是若干个相关的数据按照一定顺序并列在一起,又叫做array(数组)或List(列表),比如“浙江,江苏”。

第三种类型是mapping(映射),也就是一个名/值对(Name/value),即数据有一个名称,还有一个与之相对应的值,这又称作hash(散列)或dictionary(字典),比如“首都:北京”。

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,它的规则非常简单并且是有趣的:

1) 并列的数据之间用逗号(“,”)分隔。

2) 映射用冒号(“:”)表示。

3) 并列数据的集合(数组)用方括号("[]")表示。

4) 映射的集合(对象)用大括号(“{}”)表示。

按照这个规则可以作以下理解:

1.数组用“[]”创建,对象用“{}”创建,并且使用Json基本都是用[]或者{}创建的数组或对象,否则一个普通的字符串是没有意义的;

2.无论是数组还是对象,之间的元素都用“,”隔开;

3.对象内部,(属性的)名称和值用“:”隔开,并且必须要用“:”隔开,不可单独存在属性名或者值;

4.对象和数组可以互相嵌套,即数组中的一个元素可以是一个对象也可以是一个数组,同理对象中的一个属性的值可以是一个对象也可以是一个数组。

二、实例
下面是后台返回来的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的值了。顿时觉得自已好笨呐,那么简单的问题,都要想那么久。不行,我要去角落里哭去了。。。。

原文地址:https://www.cnblogs.com/wendy-home-5678/p/6834511.html