简体   繁体   中英

removing square brackets from JSON file in R

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM