我使用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”的总和?从json上面使用scala ??
修改
这是我试过的
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 :(得分:2)
在下面的foldLeft(B)中,最后一个表达式是一个赋值(注释掉),它返回Unit。
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
}