diff --git a/src/JSON.jl b/src/JSON.jl index fcc30e0..c57ca06 100644 --- a/src/JSON.jl +++ b/src/JSON.jl @@ -70,6 +70,35 @@ x = JSON.parse("[1,2,3]", JSONText) struct JSONText value::String end +JSON.JSONText(js::JSONText) = js + +VERSION >= v"1.11" && eval(Meta.parse("public @js_str")) + +""" + js" -> JSONText + +Construct a JSONText. String interpolation is supported via the `i` flag. +### Examples +``` +js\"\"\"alert("Hello World")\"\"\" +# JSONText("alert(\"Hello World\")") + +js\"\"\"alert("1 + 2 == \$(1 + 2)")\"\"\"i +# JSONText("alert(\"1 + 2 == 3\")") +``` +""" +macro js_str(s) + :( JSONText($(esc(s))) ) +end + +macro js_str(s, flags) + flags == "i" || @warn "Only 'i' flag currently supported (string interpolation)." + if 'i' in flags + :( JSONText($(esc(Meta.parse("\"$s\"")))) ) + else + :( JSONText($(esc(s))) ) + end +end include("lazy.jl") include("parse.jl") diff --git a/test/json.jl b/test/json.jl index 8725b43..f4341d1 100644 --- a/test/json.jl +++ b/test/json.jl @@ -107,7 +107,7 @@ end arr[3] = "b" @test JSON.json(arr) == "[\"a\",null,\"b\"]" # test custom struct writing - # defined in the test/struct.jl file + # defined in the test/parse.jl file a = A(1, 2, 3, 4) @test JSON.json(a) == "{\"a\":1,\"b\":2,\"c\":3,\"d\":4}" x = LotsOfFields("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35") @@ -256,6 +256,7 @@ end @test JSON.json(Dict(Point(1, 2) => "hi")) == "{\"1_2\":\"hi\"}" x = JSONText("[1,2,3]") @test JSON.json(x) == "[1,2,3]" + @test JSONText(x) == x @test JSON.json((a=1, b=nothing)) == "{\"a\":1,\"b\":null}" @test JSON.json((a=1, b=nothing); omit_null=true) == "{\"a\":1}" @test JSON.json((a=1, b=nothing); omit_null=false) == "{\"a\":1,\"b\":null}"