Reputation: 985
I have a json string like shown below. Is there a way to convert this to dataframe
structure("{\n \"a1\": \"2022-05-04\",\n \"inputType\": true,\n \"valDe\": \"2022-05-04\",\n \"MainNavBar\": \"V\",\n \"btna\": 0,\n \"df\": [\"CRP\", \"AS\", \"OOL\", \"GOT\", \"ANCY\"],\n \"fd\": {},\n \"fd.1\": {}\n}", class = "json")
{
"a1": "2022-05-04",
"inputType": true,
"valDe": "2022-05-04",
"MainNavBar": "V",
"btna": 0,
"df": ["CP", "AS", "OOL", "GOT", "ANCY"],
"fd": {},
"fd.1": {}
}
Expected output
df1
a1 inputType valDe MainNavBar btna df fd fd.1
2022-05-04 true 2022-05-04 V 0 c("CP", "AS", "OOL", "GOT", "ANCY") NULL NULL
Upvotes: 0
Views: 120
Reputation: 66415
library(dplyr)
library(jsonlite)
json_text %>%
fromJSON %>%
bind_cols
Result
# A tibble: 5 × 6
a1 inputType valDe MainNavBar btna df
<chr> <lgl> <chr> <chr> <int> <chr>
1 2022-05-04 TRUE 2022-05-04 V 0 CRP
2 2022-05-04 TRUE 2022-05-04 V 0 AS
3 2022-05-04 TRUE 2022-05-04 V 0 OOL
4 2022-05-04 TRUE 2022-05-04 V 0 GOT
5 2022-05-04 TRUE 2022-05-04 V 0 ANCY
Or you could add %>% tidyr::nest(df)
to put the values of df
into a list within that column:
# A tibble: 1 × 6
a1 inputType valDe MainNavBar btna data
<chr> <lgl> <chr> <chr> <int> <list>
1 2022-05-04 TRUE 2022-05-04 V 0 <tibble [5 × 1]>
Here's the output as an object you can inspect:
output = structure(list(a1 = "2022-05-04", inputType = TRUE, valDe = "2022-05-04",
MainNavBar = "V", btna = 0L, data = list(structure(list(df = c("CRP",
"AS", "OOL", "GOT", "ANCY")), class = c("tbl_df", "tbl",
"data.frame"), row.names = c(NA, -5L)))), row.names = c(NA, -1L), class = c("tbl_df", "tbl", "data.frame"))`
Upvotes: 1