【问题标题】:How to get sum of elements in nested json using scala?如何使用scala获取嵌套json中的元素总和?
【发布时间】:2014-10-10 16:30:01
【问题描述】:

我正在使用 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
 }

【问题讨论】:

  • @Bob 请看我的编辑。
  • usedBytes 属性是字符串还是长字符串?如果是字符串,则将读取getOrElse(0L).toString 的代码变为getOrElse("0")。顺便说一句,你的算法的结果是什么。它看起来一般是您需要的。
  • @bob usedBytes 很长
  • 它没有给我总和.. 它给出了预期的错误'Long' found 'unit'

标签: list scala collections


【解决方案1】:

在下面的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
}

【讨论】:

    猜你喜欢
    • 2016-12-13
    • 2022-10-24
    • 1970-01-01
    • 2015-11-13
    • 2020-07-11
    • 1970-01-01
    • 2022-07-15
    • 1970-01-01
    • 2015-03-01
    相关资源
    最近更新 更多