Scala JSON 到 DenseMatrix

Scala JSON to DenseMatrix

我正在尝试转换此 JSON 响应:

[
   {  
      "metric":"energy.salted",
      "tags":{  
         "sensor":"0",
         "unit":"101"
      },
      "aggregateTags":[  

      ],
      "dps":{  
         "1477958400":1.9519165754318237,
         "1477958401":-0.4030894637107849,
         "1477958402":0.6892277598381042,
         "1477958403":3.0232467651367188,
         "1477958404":0.07003471255302429,
         "1477958405":2.305912971496582
      }
   },
   {  
      "metric":"energy.salted",
      "tags":{  
         "sensor":"1",
         "unit":"101"
      },
      "aggregateTags":[  

      ],
      "dps":{  
         "1477958400":4.979776382446289,
         "1477958401":1.8036608695983887,
         "1477958402":3.0569913387298584,
         "1477958403":0.8318896889686584,
         "1477958404":-0.3151852488517761,
         "1477958405":2.563884735107422
      }
   }
]

进入与 "dps" 键关联的值的 DenseMatrix。最终的 DenseMatrix 应如下所示:

[
    [1.9519165754318237, -0.4030894637107849, 0.6892277598381042, 3.0232467651367188, 0.07003471255302429, 2.305912971496582],
    [4.979776382446289, 1.8036608695983887, 3.0569913387298584, 0.8318896889686584, -0.3151852488517761, 2.563884735107422]
]

我已经使用 play.api.libs.json.JSON 解析了 JSON,我什至可以使用以下方法提取 "dps" 值:

jsonResponse = Json.parse(response.body)
for (i <- 0 until numSensors) {
  dataMap = (jsonResponse.apply(i) \ "dps")
}

但是如何将其转换为具有上述格式的密集矩阵?

假设所有 dps 都有相同的键,您可以试试这个,创建一个空的 DenseMatrix 并使用 DenseMatrix.vertcat:[=12 将每个数组绑定到矩阵=]

val keys = List("1477958400", "1477958401", "1477958402", "1477958403", "1477958404", "1477958405")

var mat = new DenseMatrix[Double](0, 6, Array.empty[Double])

for (i <- 0 until numSensors) {

    val dataMap = (jsonResponse.apply(i) \ "dps")
    val array = keys.map(key => (dataMap \ key).as[Double]).toArray

    mat = DenseMatrix.vertcat(mat, new DenseMatrix[Double](1, 6, array))   
}

mat

//breeze.linalg.DenseMatrix[Double] = 1.9519165754318237  -0.4030894637107849  0.6892277598381042  ... (6 total)
//                                    4.979776382446289   1.8036608695983887   3.0569913387298584  ...