Created
July 10, 2015 01:34
-
-
Save elcritch/2ba148865ddb1adc3d51 to your computer and use it in GitHub Desktop.
Example macro to allow embedding JSON style data structures into Julia dev-v0.4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Tested on VERSION => v"0.4.0-dev+5879" | |
macro data(data) _json(data) end | |
macro json(data) _json(data) end | |
function _json(data::Any) | |
data | |
end | |
function _json(data::Expr) | |
if data.head === :cell1d | |
Expr(:call, :Dict, map(_json, data.args)...) | |
elseif data.head === :(:) | |
Expr(symbol("=>"), map(_json, data.args)...) | |
elseif data.head === :vect | |
Expr(data.head, map(_json, data.args)...) | |
elseif data.head === :curly && data.args[1] in [:json, :_, :j, :d] | |
Expr(:call, :Dict, map(_json, data.args[2:end])...) | |
else | |
throw("Unknown type: $data") | |
end | |
end | |
# syntax deprecation warning | |
@json { "a": 1, "b": 2 } | |
# Without syntax warnings by using type-prefix syntax | |
@data json{ "a": 1, "b": [3,4] } | |
@data json{ "a": 1, "b": "b": [3, d{"d": 1, "b": "b"}] } # note the "d" prefix on the inner dict | |
# Tests | |
@assert Dict("a"=>1, "b"=>2) == @json { "a": 1, "b": 2 } | |
@assert Dict(Dict("a"=>1, "b"=> [3, Dict("d"=>1, "b"=>"b")])) == @show( @data d{ "a": 1, "b": [3, d{"d": 1, "b": "b"}] }) | |
@assert Dict("a"=>1, "b"=> [3,4]) == @data json{ "a": 1, "b": [3,4] } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment