1

I am creating an JSON file from a list in R. The format of the list is quite nested.

"ageValues", whereby "ageValues" is repeated many time, always with a differnt name. The list in R looks like:

   ageBucket <-  list(startAge = 0L, endAge = 59L, price = 0, expectedInsureds = 0)

ageValue <- as.array(list(price = 0, expectedInsureds = 0))
noAgeValues <- 59
ageValues <- rep(list(ageValue), noAgeValues+1)
names(ageValues) <- c(1:60)
ageBucket <- c(ageBucket, (ageValue = list(ageValues)))
toJSON(ageBucket)

I want to create an JSOn file of this format:

...[{ "price": 0, "expectedInsureds": 0 }, ... ]...

but i am getting this instead:

...{"price":[0],"expectedInsureds":[0]},...

How can this be done, without changing the argument in toJSON(ageBucket)

i tried:

lapply(ageValues, function(x) as.array(x, letters))

but i guess i am misunderstanding something?

Nneka
  • 1,764
  • 2
  • 15
  • 39
  • Could you provide the definition of ageBucket? – matt_jay Feb 10 '21 at 14:39
  • Feel free to also look at this for how to best provide your example for others to look into it: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – matt_jay Feb 10 '21 at 14:40

1 Answers1

0

You can apply the auto_unbox = T option:

jsonlite::toJSON(ageBucket,auto_unbox = T,pretty = TRUE)

The other universal solution is to remove the square brackets in json object, e.g.

jsonlite::toJSON(ageBucket) %>% 
gsub(pattern = "\\[|\\]", replacement = "")
Peace Wang
  • 2,399
  • 1
  • 8
  • 15
  • as i mentioned in my question, i cannot change the arguments in toJSON, since it would adversely affect other parts of my file – Nneka Feb 11 '21 at 08:08
  • Have you trid the "gsub" solution?. It is not related with the arguments in toJSON – Peace Wang Feb 11 '21 at 08:29
  • as i said, ageBucket is just a section of my larger file. gsub would change the whole file, analogously to changing toJSON arguments, right? – Nneka Feb 11 '21 at 09:04
  • Alright. I still don't understand. Honestly speaking, the code I provide can satisfy "I want to create an JSOn file of this format". You say you have trid to use a function on ageValues, i.e., "lapply(ageValues, function(x) as.array(x, letters))" . In my opinion, any operation on ageValues will not solve the problem. Use gsub is an universal solution even for your larger file, it will not spend too much time. Don't struggle that it would change the whole file. Just a suggestion. Otherwise, I don't know what's the level of solution you want. – Peace Wang Feb 11 '21 at 09:30
  • Even for a simplest list, a <- list(startAge = 0L, endAge = 59L), toJSON(a) will still appear the square barckets []. – Peace Wang Feb 11 '21 at 09:43