Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Way to remove elements in json file using R

Is there a way to remove elements from a JSON using R?

Here’s an example of a file I’m working with:

[
    {
        "var1_id": 1,
        "var2_id": 2,
        "var3_id": 3
    },
    {
        "var1_id": 4,
        "var2_id": 5,
        "var3_id": 6
    },
    {
        "var1_id": 7,
        "var2_id": 8,
        "var3_id": 9
    }
]

I want to use R to remove the line for var2_id in each list, while keeping var1_id and var3_id. How could I do that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Easiest would be to convert to data.frame with fromJSON, remove the column (select) and use toJSON to convert to JSON

library(jsonlite)
library(dplyr)
fromJSON(str1) %>% 
   select(-var2_id) %>%
   toJSON(pretty = TRUE)

-output

[
  {
    "var1_id": 1,
    "var3_id": 3
  },
  {
    "var1_id": 4,
    "var3_id": 6
  },
  {
    "var1_id": 7,
    "var3_id": 9
  }
] 

data

str1 <- '[
    {
        "var1_id": 1,
        "var2_id": 2,
        "var3_id": 3
    },
    {
        "var1_id": 4,
        "var2_id": 5,
        "var3_id": 6
    },
    {
        "var1_id": 7,
        "var2_id": 8,
        "var3_id": 9
    }
]'

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading