2

I'm attempting to convert a csv into JSON format for the first time. When the csv is read into R, it's in the following data frame format:

col1   col2   col3
1       a      def1
1       b      def2
2       c      def3
2       a      def1

Ideally, I'd like to iterate through the dataframe, find the unique combinations of the three columns, and separate the key/value pairs for the JSON into the following:

{ "1":["a", "def1"], ["b", "def2"], "2":["a", "def1"], ["c", "def3"]}

I can only think of ways to achieve this in python, but I'm having difficulties executing this in R. Any suggestions on how to get this started?

1 Answers1

1

We could split the unnamed subset of columns (without the 'col1') by 'col1', and apply toJSON on it

library(jsonlite)
toJSON(split(unname(df1[-1]), df1$col1))
#{"1":[["a","def1"],["b","def2"]],"2":[["c","def3"],["a","def1"]]} 

If it needs to be ordered

toJSON(split(unname(df1[do.call(order, df1[1:2]),-1]), df1$col1))
#{"1":[["a","def1"],["b","def2"]],"2":[["a","def1"],["c","def3"]]} 

data

df1 <- structure(list(col1 = c(1L, 1L, 2L, 2L), col2 = c("a", "b", "c", 
"a"), col3 = c("def1", "def2", "def3", "def1")), class = "data.frame",
row.names = c(NA, 
-4L))
akrun
  • 874,273
  • 37
  • 540
  • 662