Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/JSON.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
3 changes: 2 additions & 1 deletion test/json.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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}"
Expand Down
Loading