How to Read and Write JSON Files in Julia (JSON.jl)
Overview
Packages that help handle JSON files in Julia include JSON.jl
, JSON3.jl
, and Serde.jl
. This document will explain JSON.jl
.
JSON.jl
is a package written in pure Julia that provides functionality for parsing and outputting JSON files. Although it is not part of Julia’s standard library, since the package is grouped under the JuliaIO group on GitHub and managed by a Julia developer, it can be considered almost an official package.
Code
Writing
Dictionary to JSON File
The code below saves a dictionary to a JSON file. By providing an indent as the third argument to JSON.print
, it is saved nicely formatted.
using JSON
dict_data = Dict("name" => "Jang, Wonyoung",
"age" => 19,
"group" => "IVE",
"nicknames" => ["Wonnyo", "Gatgi", "Lucky-Vicky"])
open("wonnyo.json", "w") do io
JSON.print(io, dict_data)
end
open("pretty_wonnyo.json", "w") do io
JSON.print(io, dict_data, 4)
end
String to JSON File
The following code saves a string to a JSON file. The basic syntax is similar to that of a dictionary, but the string must be parsed once using JSON.parse()
. Similarly, providing an indent as the third argument results in a nicely formatted file.
str_data = """
{
"name": "Jang, Wonyoung",
"age": 19,
"group": "IVE",
"nicknames": ["Wonnyo", "Gatgi", "Lucky-Vicky"]
}
"""
open("wonnyo.json", "w") do io
JSON.print(io, JSON.parse(str_data))
end
open("pretty_wonnyo.json", "w") do io
JSON.print(io, JSON.parse(str_data), 4)
end
Alternatively, you can directly save a string to a JSON file using the JSON.write
function as shown below. In this case, spaces and newlines are preserved.
str_data = """
{
"name": "Jang, Wonyoung",
"age": 19,
"group": "IVE",
"nicknames": ["Wonnyo", "Gatgi", "Lucky-Vicky"]
}
"""
unpretty_str_data = """
{"name": "Jang, Wonyoung", "age": 19, "group": "IVE", "nicknames": ["Wonnyo", "Gatgi", "Lucky-Vicky"]}
"""
open("str2json.json", "w") do io
JSON.write(io, str_data)
end
open("unpretty_str2json.json", "w") do io
JSON.write(io, unpretty_str_data)
end
Reading
You can load a JSON file with the code below.
julia> using JSON
julia> dcit_from_json = JSON.parsefile("wonnyo.json")
Dict{String, Any} with 4 entries:
"name" => "Jang, Wonyoung"
"nicknames" => Any["Wonnyo", "Gatgi", "Lucky-Vicky"]
"group" => "IVE"
"age" => 19
Alternatively, you can read it directly using an IO stream as shown:
julia> open("wonnyo.json", "r") do io
str_from_json = read(io, String)
data_from_str = JSON.parse(str_from_json)
end
Dict{String, Any} with 4 entries:
"name" => "Jang, Wonyoung"
"nicknames" => Any["Wonnyo", "Gatgi", "Lucky-Vicky"]
"group" => "IVE"
"age" => 19
Environment
- OS: Windows11
- Version: Julia 1.11.3, JSON v0.21.4