Json_str: A crate for inline json strings


#1

Hi all!

I’ve got a little crate called json_str that I’ve given a bit of :heart: this week. It takes Rust structure-literal syntax, sanitises it and outputs the result as a String:

let json = json_str!({
    a: 1,
    b: "stuff",
    c: [
        { d: -3.4 },
        { d: 1.2e+10 }
    ]
});

It now also supports simple substitution by outputting a closure that takes substitution values as arguments:

let get_json = json_fn!(|a, b, cd| {
    a: $a,
    b: $b,
    c: [
        { d: $cd },
        { d: 1.2e+10 }
    ]
});

let json = get_json("1", "\"stuff\"", "-3.4");

I’ve been using it for a while for doc tests that only show the json value, but test it has the right value behind the scenes.

It’s also my scapegoat for supporting Elasticsearch’s Query DSL.

The code still needs some work; it could be more efficient, more maintainable and more reliable. Any feedback would be much appreciated though :slight_smile: