1

I am trying to join two json objects into a single json object in R using jsonlite.

As a simple illustration, if I have the following:

The api that I am using needs a Json object that has the column names of a dataframe as the first element, followed by the numeric output of the rows. To illustrate:

df <- data.frame(A = rnorm(2), B = rnorm(2), C = rnorm(2))

Which I need to look like:

set.seed(123)

[["A", "B", "C"], [-0.5605,1.5587,0.1293],[-0.2302,0.0705,1.7151]]

But the following attempts fail at achieving the above:

c( jsonlite::toJSON( names(df) ), jsonlite::toJSON( df, "values" ))
paste0( jsonlite::toJSON( names(df) ), jsonlite::toJSON( df, "values" ))

This solution does not work, and I haven't found any other suggestions for how to achieve this.

Any ideas would be appreciated.

Nick
  • 3,262
  • 30
  • 44

1 Answers1

0

An option is to split by row (asplit with MARGIN = 1) into a list, concatenate (c) with the names of the data and apply the toJSON

library(jsonlite)
toJSON(c(list(names(df)), asplit(df, 1)))
#[["A","B","C"],[-0.5605,1.5587,0.1293],[-0.2302,0.0705,1.7151]] 
akrun
  • 874,273
  • 37
  • 540
  • 662