Search code examples
jsoniojulia

How to write a JSON object to a file to later be read in JuliaLang?


I am using this package from JuliaIO to work with JSONs; https://github.com/JuliaIO/JSON.jl

Creating some sample JSONs appears straightforward;

dict1=Dict();dict1[1]=[1,2,3];dict=Dict();dict["1"]=dict1;

and then creating a JSON from this key-value structure;

import JSON
jDict1 = JSON.json(dict)

and now I want to save it to disk so that I can read it in the future;

JSON.print(open("t1.json","w"),jDict1)

The command does not report any error, and a file name "t1.json" is created in the local folder, but it is empty with 0 bytes. How should I be writing the JSONs to file?

The documentation in the README.md mentions the IO, but I seem to be missing the concept of what and IO is referring to.


Solution

  • File's data are cached. You need to flush them. (close function is flushing too).

    You could do

    f = open("t1.json","w")
    JSON.print(f,jDict1) 
    close(f)  # or flush(f)
    

    or you could use do block syntax

    open("t1.json","w") do f
        JSON.print(f,jDict1) 
    end