2017-09-29 33 views
0

我正在R中使用巨大的JSON文件。这些JSON文件具有嵌套到列表中的列表(嵌入列表(等等))。这样就有多个层次的元素。仅使用R从JSON中提取特定级别的关键元素

我的问题是我如何只提取存储在一个特定级别的关键元素,而没有得到与他所有的嵌套列表相关的值?

,我在看那样工作的文件越来越少这样的:

{ 
    "Key 1 at level 1": "value x", 
    "Key 2 at level 1": "value x", 
    "Key 3 at level 1": { 
     "Key 1 at level 2": { 
      "Key 1 at level 3": "value x", 
      "Key 2 at level 3": "value x", 
      "Key 3 at level 3": "value x" 
     }, 
     "Key 2 at level 2": { 
      "Key 4 at level 3": "value x", 
      "Key 5 at level 3": "value x", 
      "Key 6 at level 3": "value x" 
     } 
    } 
} 

所以,在这个例子中,我想是检索,将含有“键1处第2级列表“和”2级关键2“。

您可以在这个环节发现一个真实的例子:http://bioinfo.hpc.cam.ac.uk/cellbase/webservices/rest/swagger.json(小心,因为我的巨大)

很抱歉,如果这个问题已经被问过。我花了很长时间寻找答案,但我没有找到任何答案。

在此先感谢。

+0

什么是招摇文件的问题的钥匙? – hrbrmstr

+0

也,你想要的键或值或两者? – hrbrmstr

+0

感谢您的问题。在我提供的实际示例(swagger链接)中,我想要检索的键是那些包含在键“路径”(第一级键5)中的键。正如你所看到的,有几个值包含在“路径”中(正好有97个项目)。并且每个值都会与具有相关值的另一个键开始相关。在这个第二级别的前两个键是“/ {version}/meta”,“/ {version}/meta/about”,但我想要检索所有97.但我只需要这个级别的键,我不想要所有与这些键相关的值。希望它是明确的。 – Isa

回答

0

在这种情况下,您需要每个顶级值内的键。我们可以通过将每个元素映射到它的名称来完成此操作。

这将给我们一个包含NULL s和字符向量的列表。我们unlist摆脱NULL s并把它变成一个单一的字符向量。

library('purrr') 
library('tidyverse') 
library('rjson') 

swagger <- fromJSON(' 
    { 
     "Key 1 at level 1": "value x", 
     "Key 2 at level 1": "value x", 
     "Key 3 at level 1": { 
      "Key 1 at level 2": { 
       "Key 1 at level 3": "value x", 
       "Key 2 at level 3": "value x", 
       "Key 3 at level 3": "value x" 
      }, 
      "Key 2 at level 2": { 
       "Key 4 at level 3": "value x", 
       "Key 5 at level 3": "value x", 
       "Key 6 at level 3": "value x" 
      } 
     } 
    } 
') 
map(swagger, names) %>% unlist 

[1] "Key 1 at level 2" "Key 2 at level 2"

+0

谢谢!这非常有用。 将您的建议后,我做了以便与不同层次的应用到其他文件变化不大: > all_keys < - 地图(招摇,名) > all_keys $'键1在水平1' NULL $'键2在水平1' NULL $'在水平键3 1' [1] “键1在第2级” 第2级 “ > all_keys $”键3 1级“ 键2 “ [1]”级别2的密钥1“”级别2的密钥2“ – Isa