Skip to main content

json

Macro json 

Source
macro_rules! json {
    (null) => { ... };
    ([]) => { ... };
    ([ $($elem:tt)+ ]) => { ... };
    ({}) => { ... };
    ({ $($member:tt)+ }) => { ... };
    ($other:expr) => { ... };
}
Expand description

Construct a Value from JSON-ish literal syntax.

use edikt_core::{Value, json};

let v = json!({
    "name": "edikt",
    "version": 1,
    "lossless": true,
    "formats": ["jsonc", "toml", "yaml"],
    "parent": null,
});
assert_eq!(v.to_json(), r#"{"name":"edikt","version":1,"lossless":true,"formats":["jsonc","toml","yaml"],"parent":null}"#);

Keys may be literals or parenthesised expressions, and any value position accepts an expression that converts into a Value:

use edikt_core::{Value, json};

let key = "dynamic";
let count = 3_i64;
let v = json!({ (key): count, "doubled": count * 2 });
assert_eq!(v.to_json(), r#"{"dynamic":3,"doubled":6}"#);

Nesting, arrays, and trailing commas all work:

use edikt_core::{Value, json};

let v = json!([1, [2, 3], { "k": [true, null] },]);
assert_eq!(v.to_json(), r#"[1,[2,3],{"k":[true,null]}]"#);