0

I am creating a JSON file in R:

test <- c(list(item1 = "TEXT",
               item2 = as.array(list(start = 0,
                                     end = 99))))

write_json(test, path = "test.json" , auto_unbox = TRUE , null = "null")

which results in :

{"item1":"INDIVIDUAL_AGE","item2":{"start":[0],"end":[99]}}

however I need the result to be:

{"item1":"INDIVIDUAL_AGE","item2":{"start":0,"end":99}}

how can I get rid of the square brackets from item2 elements?

Nneka
  • 1,764
  • 2
  • 15
  • 39

1 Answers1

0

For auto_unbox, jsonlite::toJSON recommends unbox:

auto_unbox: automatically 'unbox' all atomic vectors of length 1. It is
          usually safer to avoid this and instead use the 'unbox'
          function to unbox individual elements. An exception is that
          objects of class 'AsIs' (i.e. wrapped in 'I()') are not
          automatically unboxed. This is a way to mark single values as
          length-1 arrays.

For that, we can use rapply:

library(jsonlite)
toJSON(
  rapply(test, function(z) if (length(z) == 1L) unbox(z) else z,
         how = "replace")
)
# {"item1":"TEXT","item2":{"start":0,"end":99}} 

(Also works inside write_json.)

... though it does seem odd to me that auto_unbox=TRUE is not working here.

r2evans
  • 141,215
  • 6
  • 77
  • 149
  • is there a different was how to do this ? I only chose a snippet of the .JSON I am working on, but by using the provided solution I would have to apply this to the entire JSON. – Nneka Jan 10 '22 at 14:55
  • I know of no other way. I thought `auto_unbox=TRUE` would be the canonical way, but reading the help doc suggests otherwise. Frankly I'd think this is a bug somehow, and should be raised as one. Regardless, is there a reason you cannot use `rapply` on your entire dataset? – r2evans Jan 10 '22 at 14:56