2017-01-30 76 views
0

我有一個JSON輸入,我從服務器獲取,我想將其解析爲數據框對象。在R中解析多行JSON

結構:

體積緊湊

'{"total_rows":2,"offset":0,"rows":[{"id":"1","key":["1001"],"value":{"context":"1001","application_id":"1","cust_assets_total":1550000}},{"id":"2","key":["1001"],"value":{"context":"1001","application_id":"2","cust_assets_total":1550000}}]}' 

漂亮的表格

{ 
    "total_rows": 2, 
    "offset": 0, 
    "rows": [ 
    { 
     "id": "1", 
     "key": [ 
     "1001" 
     ], 
     "value": { 
     "context": "1001", 
     "application_id": "1", 
     "cust_assets_total": 1550000 
     } 
    }, 
    { 
     "id": "2", 
     "key": [ 
     "1001" 
     ], 
     "value": { 
     "context": "1001", 
     "application_id": "2", 
     "cust_assets_total": 1550000 
     } 
    } 
    ] 
} 

預期輸出:

context application_id cust_assets_total 
1001 1    1550000 
1001 2    1550000 

代碼中使用:

library(jsonlite) 

raw_data <- '{"total_rows":2,"offset":0,"rows":[{"id":"1","key":["1001"],"value":{"context":"1001","application_id":"1","cust_assets_total":1550000}},{"id":"2","key":["1001"],"value":{"context":"1001","application_id":"2","cust_assets_total":1550000}}]}' 

temp <-fromJSON(paste(readLines(raw_data),collapse="")) 

,但是這導致錯誤:

Error in file(con, "r") : cannot open the connection 
In addition: Warning message: 
In file(con, "r") : 
    cannot open file '{"total_rows":2,"offset":0,"rows":[{"id":"1","key":["1001"],"value":{"context":"1001","application_id":"1","cust_assets_total":1550000}},{"id":"2","key":["1001"],"value":{"context":"1001","application_id":"2","cust_assets_total":1550000}}]}': No such file or directory 
+0

如果'raw_data'已經在R中,爲什麼不只是'fromJSON(raw_data)'?至於錯誤,我相信你可能會丟失'textConnection',如'readLines(textConnection(raw_data))' – Jota

+0

raw_data將是使用Rcurl下載的,即raw_data < - getURL(url),將檢查你的建議 –

回答

0

你可以readlines方法,如果你包裹textConnection圍繞 「raw_data」,但它更容易離開它:

> temp <-fromJSON(raw_data) 
> temp 
$total_rows 
[1] 2 

$offset 
[1] 0 

$rows 
    id key value.context value.application_id value.cust_assets_total 
1 1 1001   1001     1     1550000 
2 2 1001   1001     2     1550000 

注意:...此版本的fromJSON爲您提供了三元素的指定列表。

+0

感覺啞巴現在問這個問題,謝謝你的解決方案 –