Valentin_Ștefan
Valentin_Ștefan

Reputation: 6446

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

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.

Upvotes: 1

Views: 359

Answers (1)

r2evans
r2evans

Reputation: 160607

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)

Upvotes: 1

Related Questions