Json in Julia

Julia offers built-in support for JSON encoding and decoding, including to and from built-in and custom data types.

using JSON

# We'll use these two structs to demonstrate encoding and
# decoding of custom types below.
struct Response1
    page::Int
    fruits::Vector{String}
end

# Only fields with values will be encoded/decoded in JSON.
struct Response2
    page::Int
    fruits::Vector{String}
end

function main()
    # First we'll look at encoding basic data types to
    # JSON strings. Here are some examples for atomic values.
    bolB = JSON.json(true)
    println(bolB)

    intB = JSON.json(1)
    println(intB)

    fltB = JSON.json(2.34)
    println(fltB)

    strB = JSON.json("gopher")
    println(strB)

    # And here are some for arrays and dictionaries, which encode
    # to JSON arrays and objects as you'd expect.
    slcD = ["apple", "peach", "pear"]
    slcB = JSON.json(slcD)
    println(slcB)

    mapD = Dict("apple" => 5, "lettuce" => 7)
    mapB = JSON.json(mapD)
    println(mapB)

    # The JSON package can automatically encode your
    # custom data types. It will include all fields
    # in the encoded output.
    res1D = Response1(1, ["apple", "peach", "pear"])
    res1B = JSON.json(res1D)
    println(res1B)

    res2D = Response2(1, ["apple", "peach", "pear"])
    res2B = JSON.json(res2D)
    println(res2B)

    # Now let's look at decoding JSON data into Julia
    # values. Here's an example for a generic data structure.
    byt = """{"num":6.13,"strs":["a","b"]}"""

    # We need to parse the JSON string into a Julia structure.
    # This `Dict{String,Any}` will hold a dictionary of strings
    # to arbitrary data types.
    dat = JSON.parse(byt)
    println(dat)

    # We can access values in the decoded data directly.
    num = dat["num"]
    println(num)

    # Accessing nested data is straightforward.
    strs = dat["strs"]
    str1 = strs[1]
    println(str1)

    # We can also decode JSON into custom data types.
    # This has the advantages of adding additional
    # type-safety to our programs.
    str = """{"page": 1, "fruits": ["apple", "peach"]}"""
    res = JSON.parse(str, Response2)
    println(res)
    println(res.fruits[1])

    # In the examples above we always used strings as
    # intermediates between the data and JSON representation.
    # We can also stream JSON encodings directly to IO streams.
    d = Dict("apple" => 5, "lettuce" => 7)
    JSON.print(stdout, d)
    println()
end

main()

To run the program, save it as json_example.jl and use julia json_example.jl.

$ julia json_example.jl
true
1
2.34
"gopher"
["apple","peach","pear"]
{"apple":5,"lettuce":7}
{"page":1,"fruits":["apple","peach","pear"]}
{"page":1,"fruits":["apple","peach","pear"]}
Dict("num" => 6.13, "strs" => ["a", "b"])
6.13
a
Response2(1, ["apple", "peach"])
apple
{"apple":5,"lettuce":7}

We’ve covered the basics of JSON in Julia here, but check out the JSON.jl documentation for more details.

Julia’s JSON handling is similar to Go’s, with some differences:

  1. Julia uses the JSON package, which needs to be imported explicitly.
  2. Julia’s JSON.json() function is used for encoding, similar to Go’s json.Marshal().
  3. Julia’s JSON.parse() function is used for decoding, similar to Go’s json.Unmarshal().
  4. Julia uses Dict instead of Go’s map for key-value pairs.
  5. Julia’s struct fields are public by default, unlike Go where only capitalized fields are exported.
  6. Julia doesn’t use pointer syntax (&) for passing references.

The overall structure and functionality remain similar, making it easy to work with JSON in both languages.