關於json數組對象和對象數組遇到的一些問題

###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的值了。頓時以爲自已好笨吶,那麼簡單的問題,都要想那麼久。不行,我要去角落裏哭去了。。。。

相關文章
相關標籤/搜索