Why does Julia not support JSON syntax to create a Dict?

Joining late…
I’ve asked about this separately.

This is the code I can up with. Maybe it’s of use to someone…


json(n) = n
json(n::Symbol) = esc(n)

function json(n::Expr)
    if n.head == :vect
        return Expr(:vect, map(json, n.args)...)
    elseif n.head == :braces
        kv = []
        for f in n.args
            f isa Expr || error("not a valid JSON")
            f.args[1] == :(:) || error("not a valid JSON")
            k = f.args[2]

            typeof(k) ∈ (Symbol, String) || error("not a valid JSON")
            k = string(k)
            v = json(f.args[3])
            push!(kv, :($k=>$v))
        end
        return :(Dict{String, Any}($(kv...)))
    else
        return esc(n)
    end
end

macro json(n)
    return json(n)
end

function aa()
    i = 2
    j = 3
    return @json({
                a : {  # recursive...
                    b : i, # accessing local variable
                    e : nothing,
                }, "c": [1, 2.0, "mixed types"], # array
                "d": i + j # expression
            })
end

aa()
#Dict{String, Any} with 3 entries:
#  "c" => Any[1, 2.0, "mixed types"]
#  "a" => Dict{String, Any}("e"=>nothing, "b"=>2)
#  "d" => 5

Thanks,
DD

2 Likes