Home > Mobile >  How to keep the same format as original file when writing a JSON file
How to keep the same format as original file when writing a JSON file

Time:10-08

I tried out the functionality of the R package jsonlite and not sure why the writting function modifies a bit the structure of the file.

Below is a simple example of a file with a given specific structure. I read it and then write it back to disk, but something minor changes and I cannot open it with the 3rd party app that created it in the first place.

library(jsonlite)

json_lst <- fromJSON(txt = "https://raw.githubusercontent.com/valentinitnelav/test/master/test.json")
write_json(json_lst, "./test/test_2.json")

Could you help me understand what exactly changes and fix this issue?

I opened the two files with the Mozzila browser and it might be that some lists lose some elements somehow (get "unlisted" possibly, but not all). maybe something happens during the toJSON() operation, but not sure what exactly.

CodePudding user response:

Up front, add auto_unbox = TRUE.

jsonlite's default behavior is to strictly "box" vectors of length 1.

toJSON(list(a=1))
# {"a":[1]} 
toJSON(list(a=1), auto_unbox=TRUE)
# {"a":1} 

So for your code, use

write_json(json_lst, "./test/test_2.json", auto_unbox = TRUE)
  • Related