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?