2014-10-10 84 views
0

我使用Scala的處理嵌套的JSON如何使用scala獲取嵌套json中的元素總和?

"disks" : [ { 
"name" : "v2.16", 
"diskAggregate" : "aggr0", 
"diskRPM" : 15000, 
"totalSizeBytes" : 1077477376, 
"vendorId" : "NETAPP ", 
"usedBytes" : 1070071808, 
"diskType" : "FCAL", 
"uuid" : "4E455441:50502020:56442D31:3030304D:422D465A:2D353230:32353836:30303030:00000000:00000000", 
"portName" : "FC:A ", 
"raidGroup" : "rg0" 
}, 
{ 
"name" : "v4.16", 
"diskAggregate" : "aggr0", 
"diskRPM" : 15000, 
"totalSizeBytes" : 1077477376, 
"vendorId" : "NETAPP ", 
"usedBytes" : 1070071808, 
"diskType" : "FCAL", 
"uuid" : "4E455441:50502020:56442D31:3030304D:422D465A:2D353230:32353633:34333030:00000000:00000000", 
"portName" : "FC:B ", 
"raidGroup" : "rg0" 
}] 

我想在JSON數組的所有JSON對象獲得「usedBytes」的總和。 如何從scala使用json獲得'usedBytes'的總和?

編輯:

這裏是我試圖

val datastoreCapacity = disks 
val usableSpace = datastoreCapacity.foldLeft(0L) { 
case (sumOfUsedSpace, esxDevice) => 
    val sumOfTotalBytesOnStorageDevice = esxDevice.datastores.foldLeft(0L) { 
    case (totalBytesOnDevice, datastore) => 
    // totalBytesOnDevice + ut..getOrElse(0L).toString.toLong 
    val sum = datastore.utilization.foldLeft(0L) { 
     case (total,util) => 
     total + util.usedBytes.getOrElse(0L).toString.toLong 
    } 
    } 
    sumOfUsedSpace + sumOfTotalBytesOnStorageDevice 
} 
+0

@Bob請參閱我的編輯。 – user3322141 2014-10-10 16:34:26

+0

'usedBytes'屬性是字符串還是long?如果是字符串,則將讀取'getOrElse(0L).toString'的代碼變爲'getOrElse(「0」)'。順便說一句,你的算法的結果是什麼。它通常看起來你需要什麼。 – 2014-10-10 16:38:49

+0

@bob usedBytes很長 – user3322141 2014-10-10 16:47:36

回答

2

在foldLeft(B)所示,最後一個表達式是一個賦值(註釋),它返回單元。

val datastoreCapacity = disks 
val usableSpace = datastoreCapacity.foldLeft(0L) { // A 

    case (sumOfUsedSpace, esxDevice) => 
     val sumOfTotalBytesOnStorageDevice = esxDevice.datastores.foldLeft(0L) { // B 

      case (totalBytesOnDevice, datastore) => 
        // totalBytesOnDevice + ut..getOrElse(0L).toString.toLong 
        /* Note --> val sum = */ // assignment returns Unit 
        datastore.utilization.foldLeft(0L) { // C 

         case (total,util) => 
          total + util.usedBytes.getOrElse(0L).toString.toLong 
        } 

     } 
     sumOfUsedSpace + sumOfTotalBytesOnStorageDevice 
}