Home > front end >  Way to remove elements in json file using R
Way to remove elements in json file using R

Time:08-20

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?

CodePudding user response:

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
    }
]'

  • Related