Reading and Writing JSON Files in Julia (JSON3.jl)
Overview
Packages that facilitate handling JSON files in Julia include JSON.jl
, JSON3.jl
, and Serde.jl
. This document provides an explanation of JSON3.jl
.
JSON3.jl
is a package written purely in Julia, offering functionality to parse and output JSON files. Unlike JSON.jl
, it is not grouped under JuliaIO on GitHub, but is managed in a personal repository.
Code
Writing
Saving a dictionary to a JSON file
You can save a dictionary to a JSON file with the following code.
using JSON3
dict_data = Dict("name" => "Jang, Wonyoung",
"age" => 20,
"group" => "IVE",
"nicknames" => ["Wonnyo", "Gatgi", "Lucky-Vicky"])
# 딕셔너리를 json 파일로 저장
JSON3.write("wonnyo.json", dict_data)
# 혹은
open("wonnyo.json", "w") do io
JSON3.write(io, dict_data)
end
# 예쁘게 저장
open("pretty_wonnyo.json", "w") do io
JSON3.pretty(io, dict_data)
end
Saving a string to a JSON file
For strings, you can use a similar approach to dictionaries, but it requires parsing with JSON3.read
before passing to the JSON3.write
function.
str_data = """
{
"name": "Jang, Wonyoung",
"age": 20,
"group": "IVE",
"nicknames": ["Wonnyo", "Gatgi", "Lucky-Vicky"]
}
"""
# 문자열을 json 파일로 저장
JSON3.write("wonnyo.json", JSON3.read(str_data))
# 예쁘게 저장
open("pretty_wonnyo.json", "w") do io
JSON3.pretty(io, str_data)
end
Reading
The JSON3.read
function allows you to load JSON files as if they were dictionaries. The reason it’s referred to as “as if” is because it is actually not a dictionary but a separate type called JSON3.Object
. You can directly convert it to a dictionary using the Dict
function. To load it as a string, you can simply use the read
function.
julia> json_data = JSON3.read("wonnyo.json")
JSON3.Object{Vector{UInt8}, Vector{UInt64}} with 4 entries:
:name => "Jang, Wonyoung"
:age => 20
:group => "IVE"
:nicknames => ["Wonnyo", "Gatgi", "Lucky-Vicky"]
julia> json_data[:name]
"Jang, Wonyoung"
julia> Dict(json_data)
Dict{Symbol, Any} with 4 entries:
:group => "IVE"
:age => 20
:name => "Jang, Wonyoung"
:nicknames => ["Wonnyo", "Gatgi", "Lucky-Vicky"]
julia> str_from_json = read("wonnyo.json", String)
"{\"name\":\"Jang, Wonyoung\",\"age\":20,\"group\":\"IVE\",\"nicknames\":[\"Wonnyo\",\"Gatgi\",\"Lucky-Vicky\"]}"
Environment
- OS: Windows11
- Version: Julia 1.11.3, JSON3 v1.14.2