0

I searched the forum and couldn't find a similar question, so I apologize if I may have missed it.

Simply, i am given a JSON file and I want to create it. So I thought an easy way to do this is by parsing the file with fromJSON function from jsonlite package and see how the R Object is structured, and then try to create the JSON file by first creating the R object and using the function toJSON.

The JSON file that I am given is the following:

[[{"name":"Wine"},{"data":[{"rating":"23.45","month":8,"year":2012,"day":8},{"rating":"23.66","month":8,"year":2012,"day":9},{"rating":"24.75","month":8,"year":2013,"day":9},{"rating":"24.97","month":8,"year":2013,"day":12}]}]]

Parsing the above JSON file with fromJSON function gives the following object:

str(object)

List of 1
$ :'data.frame':    2 obs. of  2 variables:
  ..$ name: chr [1:2] "Wine" NA
  ..$ data:List of 2
  .. ..$ : NULL
  .. ..$ :'data.frame': 248 obs. of  4 variables:
  .. .. ..$ rating: chr [1:248] "23.45" "23.66" "23.59" "23.48" ...
  .. .. ..$ month : int [1:248] 8 8 8 8 8 8 8 8 8 8 ...
  .. .. ..$ year  : int [1:248] 2012 2012 2012 2012 2012 2012 2012 2012 ...
  .. .. ..$ day   : int [1:248] 8 9 10 13 14 15 16 17 20 21 ...

Creating the above object. The values are random

name = c("Wine", NA)
data = list(NULL, data.frame(rating = as.character(c(1:248)), month = as.integer(rep(12, 248)), year = as.integer(rep(1940, 248)), day = as.integer(rep(31, 248)), stringsAsFactors = FALSE))
result = data.frame(name, data)

The last line gives the error:

Error in data.frame(NULL, list(rating = c("1", "2", "3", "4", "5", "6",  :   arguments imply differing number of rows: 0, 248

Anyone have an idea?

1 Answers1

0

Apparently the data.frame() function recurses into the second element of the list it receives or something like that.

A possible approach to build such a data frame as in your original example is to replace the column, e.g.:

result <- data.frame(name=name,data=NA)
result$data <- data

Then you have as required:

str(result)

'data.frame':   2 obs. of  2 variables:
 $ name: Factor w/ 1 level "Wine": 1 NA
 $ data:List of 2
  ..$ : NULL
  ..$ :'data.frame':    248 obs. of  4 variables:
  .. ..$ rating: chr  "1" "2" "3" "4" ...
  .. ..$ month : int  12 12 12 12 12 12 12 12 12 12 ...
  .. ..$ year  : int  1940 1940 1940 1940 1940 1940 1940 1940 1940 1940 ...
  .. ..$ day   : int  31 31 31 31 31 31 31 31 31 31 ...
Marco Torchiano
  • 712
  • 7
  • 21