按对象属性在列表中获取对象

时间:2014-01-15 18:27:11

标签: json r list object

简而言之,我有这个json结构

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

列表条目是来自特定类的所有对象(例如,由id和名称表示的结果)。我用RJSONIO读了这个json。

现在我需要一个能给我任何id的“名字”的函数。所以首选用法是:

setting = settings2id(2) #=222

有人可以帮忙吗?

1 个答案:

答案 0 :(得分: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"