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

**URL:** https://discourse.julialang.org/t/why-does-julia-not-support-json-syntax-to-create-a-dict/42873
**Category:** Internals & Design
**Tags:** json
**Created:** [July 10, 2020, 9:32pm UTC](https://discourse.julialang.org/t/why-does-julia-not-support-json-syntax-to-create-a-dict/42873 "2020-07-10T21:32:04Z")
**Posts on this page:** 8
**Page:** 2

<div class="post-metadata">

### Author: ![simeonschaub](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/simeonschaub/32/216566_2.png) [@simeonschaub](https://discourse.julialang.org/u/simeonschaub)
#### Post date: [July 13, 2020, 11:46am UTC](https://discourse.julialang.org/t/why-does-julia-not-support-json-syntax-to-create-a-dict/42873/21 "2020-07-13T11:46:24Z")

</div>

Macros can only operate on syntactically valid Julia code, since they always operate on expression objects. Single quotes (`'`) in Julia always denote single-character literals, so something like `'abc'` is not valid syntax, so this will error during parsing. Disallowing multi-character strings enclosed with single quotes was a conscious decision, because otherwise you would get parsing ambiguities, since `'` is also a postfix operator for `adjoint`. For this specific case, a [non-standard string literal](https://docs.julialang.org/en/v1/manual/metaprogramming/index.html#Non-Standard-String-Literals-1) would probably make more sense.

---

<div class="post-metadata">

### Author: ![Tero\_Frondelius](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tero_frondelius/32/7629_2.png) [@Tero\_Frondelius](https://discourse.julialang.org/u/Tero_Frondelius)
#### Post date: [July 13, 2020, 12:00pm UTC](https://discourse.julialang.org/t/why-does-julia-not-support-json-syntax-to-create-a-dict/42873/22 "2020-07-13T12:00:59Z")

</div>

Thanks for the explanation. Did I understood you correctly that:

```julia
@js { d: 'thirty', 123 } 

```

is not possible, but

```julia
js"{ d: 'thirty', 123 }" 

```

could be?

---

<div class="post-metadata">

### Author: ![simeonschaub](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/simeonschaub/32/216566_2.png) [@simeonschaub](https://discourse.julialang.org/u/simeonschaub)
#### Post date: [July 13, 2020, 12:47pm UTC](https://discourse.julialang.org/t/why-does-julia-not-support-json-syntax-to-create-a-dict/42873/24 "2020-07-13T12:47:33Z")

</div>

Yes! It should be as simple as:

```julia
using JSON3
macro js_str(s)
    return :(JSON3.read($s))
end

```

---

<div class="post-metadata">

### Author: ![Tero\_Frondelius](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tero_frondelius/32/7629_2.png) [@Tero\_Frondelius](https://discourse.julialang.org/u/Tero_Frondelius)
#### Post date: [July 13, 2020, 1:24pm UTC](https://discourse.julialang.org/t/why-does-julia-not-support-json-syntax-to-create-a-dict/42873/25 "2020-07-13T13:24:15Z")

</div>

Thanks. Pretty cool! However, the same problem persists:

```julia
julia> using JSON3

julia> macro js_str(s)
           return :(JSON3.read($s))
       end
@js_str (macro with 1 method)

julia> js"{\"a_number\" : 5.0, \"an_array\" : [\"string\", 9]}"
Dict{String,Any} with 2 entries:
  "an_array" => Any["string", 9]
  "a_number" => 5.0

julia> js"{'a_number' : 5.0, 'an_array' : ['string', 9]}"
ERROR: Invalid object key
Line: 0
Around: ...{'a_number' : 5.0, 'an...
            ^

Stacktrace:
 [1] error(::String) at .\error.jl:33
 [2] _error(::String, ::JSON.Parser.MemoryParserState) at C:\Users\tfr004\.julia\packages\JSON\d89fA\src\Parser.jl:142
 [3] parse_object(::JSON.Parser.ParserContext{Dict{String,Any},Int64,true,nothing}, ::JSON.Parser.MemoryParserState) at C:\Users\tfr004\.julia\packages\JSON\d89fA\src\Parser.jl:227
 [4] parse_value(::JSON.Parser.ParserContext{Dict{String,Any},Int64,true,nothing}, ::JSON.Parser.MemoryParserState) at C:\Users\tfr004\.julia\packages\JSON\d89fA\src\Parser.jl:168
 [5] #parse#1(::Type, ::Type{Int64}, ::Bool, ::Nothing, ::typeof(JSON.Parser.parse), ::String) at C:\Users\tfr004\.julia\packages\JSON\d89fA\src\Parser.jl:463
 [6] parse(::String) at C:\Users\tfr004\.julia\packages\JSON\d89fA\src\Parser.jl:461
 [7] top-level scope at REPL[16]:1

julia>

```

---

<div class="post-metadata">

### Author: ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)
#### Post date: [July 13, 2020, 1:41pm UTC](https://discourse.julialang.org/t/why-does-julia-not-support-json-syntax-to-create-a-dict/42873/26 "2020-07-13T13:41:23Z")

</div>

> [@Tero\_Frondelius](#):
>
> the same problem persists

Possibly because `'key'` is not [valid JSON syntax](https://www.json.org/json-en.html). You need `"key"`. And then probably you want `"""` to make your life easier, eg

```julia
julia> js"""{"a_number" : 5.0, "an_array" : ["string", 9]}"""
JSON3.Object{Base.CodeUnits{UInt8,String},Array{UInt64,1}} with 2 entries:
  :a_number => 5
  :an_array => Any["string", 9]

```

---

<div class="post-metadata">

### Author: ![anon67531922](https://avatars.discourse-cdn.com/v4/letter/a/48db29/32.png) [@anon67531922](https://discourse.julialang.org/u/anon67531922)
#### Post date: [July 13, 2020, 8:57pm UTC](https://discourse.julialang.org/t/why-does-julia-not-support-json-syntax-to-create-a-dict/42873/27 "2020-07-13T20:57:41Z")

</div>

Have a look at Simon’s JSServe.jl

[https://github.com/SimonDanisch/JSServe.jl](https://github.com/SimonDanisch/JSServe.jl)

It might be of some interest 🙂

---

<div class="post-metadata">

### Author: ![anon67531922](https://avatars.discourse-cdn.com/v4/letter/a/48db29/32.png) [@anon67531922](https://discourse.julialang.org/u/anon67531922)
#### Post date: [July 13, 2020, 9:02pm UTC](https://discourse.julialang.org/t/why-does-julia-not-support-json-syntax-to-create-a-dict/42873/28 "2020-07-13T21:02:56Z")

</div>

Try this

```julia
julia> js"""
       {
           "a_number" : 5.0,
           "an_array" : ["string", 9]
       }
       """
JSON3.Object{Base.CodeUnits{UInt8,String},Array{UInt64,1}} with 2 entries:
  :a_number => 5
  :an_array => Any["string", 9]

```

🙂

Edit: If you really wanted a `Dict`, just do this

```julia
julia> macro js_str(s)
           return :(Dict(JSON3.read($s)))
       end
@js_str (macro with 1 method)

julia> js"""
       {
           "a_number" : 5.0,
           "an_array" : ["string", 9]
       }
       """
Dict{Symbol,Any} with 2 entries:
  :a_number => 5
  :an_array => Any["string", 9]

```

🤓

---

<div class="post-metadata">

### Author: ![dodoplus](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dodoplus/32/30148_2.png) [@dodoplus](https://discourse.julialang.org/u/dodoplus)
#### Post date: [April 25, 2022, 3:27pm UTC](https://discourse.julialang.org/t/why-does-julia-not-support-json-syntax-to-create-a-dict/42873/29 "2022-04-25T15:27:55Z")

</div>

Joining late…  
I’ve asked about [this](https://discourse.julialang.org/t/json-bson-dsl/79940) separately.

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

```julia

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

[Previous page](https://discourse.julialang.org/t/why-does-julia-not-support-json-syntax-to-create-a-dict/42873.md?page=1)
