2017-03-03 158 views
0

我想轉換此JSON響應:斯卡拉JSON到DenseMatrix

[ 
    { 
     "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") 
} 

但是,如何將它轉換爲具有上述格式的密集矩陣?

回答

1

假設你有相同的密鑰對所有DPS,你可以試試這個,創建一個空DenseMatrix每個數組綁定到矩陣DenseMatrix.vertcat

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 ... 
+0

這幫助了很多隊友謝謝!無論如何,horzcat可以做同樣的事情嗎?我嘗試將mat初始化爲'var mat = new DenseMatrix [Double](6,0,Array.empty [Double])',並使用'mat = DenseMatrix.horzcat(mat,new DenseMatrix [Double](6,1,array ))''但編譯器告訴我有6行0列是不可能的lol – Chirag

+0

更具體地說,編譯器說'java.lang.IndexOutOfBoundsException:MajorStride == 1小於行== 5,這是不可能的我正在執行'horizcat'的行。我可能錯誤地解釋了這一點。 – Chirag

+1

這看起來像[問題](https://github.com/scalanlp/breeze/issues/488)。順便說一句,你總是可以做'vertcat',然後用'mat.t'轉置矩陣。雖然不理想。 – Psidom