mat
mat

Reputation: 2617

json to dataframe

I have a data.json file that looks like this:

{
  "A" : {
    "data" : "a1 aa2 aaa3\na4 aa5 aaa6\na7 aa8 aaa9"
  },
  "B" : {
    "data" : "b1 bb2 bbb3\nb4 bb5 bbb6\nb7 bb8 bbb9"
  },
  "C" : {
    "data" : "c1 cc2 ccc3\nc4 cc5 ccc6\nc7 cc8 ccc9"
  }
}

I want to convert this to a list of data frames (called output), one data.frame for each capital letter. The string "\n" distinguishes the rows within a data frame. Each data frame should looks like this:

> print(output[[1]])

   X1   X2    X3
1  a1  aa2  aaa3
2  a4  aa5  aaa6
3  a7  aa8  aaa9

> print(output[[2]])

   X1   X2    X3
1  b1  bb2  bbb3
2  b4  bb5  bbb6
3  b7  bb8  bbb9

#and so on...

Upvotes: 1

Views: 50

Answers (1)

akuiper
akuiper

Reputation: 214927

Simply load the json file as list using rjson/jsonlite library, and read each string as data frame with read.table function:

lapply(rjson::fromJSON(file = "data.json"), function(x) read.table(text = x$data))

#$A
#  V1  V2   V3
#1 a1 aa2 aaa3
#2 a4 aa5 aaa6
#3 a7 aa8 aaa9

#$B
#  V1  V2   V3
#1 b1 bb2 bbb3
#2 b4 bb5 bbb6
#3 b7 bb8 bbb9

#$C
#  V1  V2   V3
#1 c1 cc2 ccc3
#2 c4 cc5 ccc6
#3 c7 cc8 ccc9

Upvotes: 1

Related Questions