2014-01-15 78 views
1

我有此JSON結構列表內獲取對象由對象在短屬性

{ 
"inputSettings": [ 
    { "id":  1,"name": "111" }, 
    { "id":  2,"name": "222" }, 
    { "id":  3,"name": "333" } 
    ... 
] 
} 

列表條目是從(其由一個ID和一個名稱表示例如結果)的特定類的所有對象。我用RJSONIO閱讀這個json。

現在我需要一個函數,它給我任何id的「名稱」。所以最喜歡的用法是:

setting = settings2id(2) #=222 

任何人都可以幫忙嗎?

+2

歡迎來到SO。現在,這聽起來像你要求我們爲你寫代碼。這不是什麼意思。相反,嘗試幾件事情,並在這裏分享。然後問你的問題,解釋爲什麼你的方法不起作用。 – Justin

+0

它看起來很基本:使用fromJSON(text)讀取json並獲得像json一樣的結構列表;將該列表轉換爲更簡單的子集(例如矩陣或data.frame)然後使用它。你有沒有按照這些步驟?如果是這樣,哪一步給你帶來麻煩? – digEmAll

+0

好吧這裏是... 'a = do.call(rbind.data.frame,biglistFROMJson $ inputSettings)' '$ $ name [which(a $ id == 3)]'這給了我333和'級別:111 222 333'我如何禁用電平輸出? – user3199454

回答

1

要獲得通過id訪問名稱的最大速度,可以使用data.table包例如: (它也解決了「因素問題」,而不改變全局選項)

library(RJSONIO) 
library(data.table) 

txt <- 
    '{ 
    "inputSettings": [ 
    { "id":  1,"name": "111" }, 
    { "id":  2,"name": "222" }, 
    { "id":  3,"name": "333" } 
    ] 
}' 

a <- fromJSON(txt) 

# turn the list into a data.table 
DT <- rbindlist(a$inputSettings) 

# set id as data.table key to get maximum look-up speed 
setkeyv(DT,cols='id') 

# get the name corresponding to 2 
# N.B. the lookup is performed using binary search for maximum speed 
name <- DT[J(2)]$name 

# > [1] "222"