1

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.

Valentin_Ștefan
  • 6,130
  • 2
  • 45
  • 68
  • keys can get re-ordered across implementations, but you shouldn't be losing elements. – dandavis Oct 07 '21 at 20:03
  • @dandavis, is this an issue with `jsonlite` package when writing a JSON file? The answer of @r2evans seems to solve my problem, and when I read both files in R, they are identical. I hope all is good so far, because I have hundreds of these files and I don't want some hidden issue :D – Valentin_Ștefan Oct 08 '21 at 08:44
  • that all makes sense, i wouldn't worry about it. – dandavis Oct 08 '21 at 14:15

1 Answers1

1

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)
r2evans
  • 141,215
  • 6
  • 77
  • 149