Skip to main content

json

Macro json 

Source
macro_rules! json {
    ($($tt:tt)+) => { ... };
}
Expand description

Builds a Value from JSON-like syntax.

null, true, false, arrays [...], and objects {...} are written as in JSON, nested to any depth. Anything else is a Rust expression converted with Value::from, so variables, numbers, strings, Options, Vecs, and other values drop straight in. An object key is a string literal, or any expression in parentheses that converts into Cow<str> (a &str or a String).

Members are appended in the order written, as Object::push does; a key written twice appears twice. An expression containing a top-level comma (a generic with two parameters, say) must be wrapped in parentheses.

Size. The macro takes items that are a single token (1, "s", x, null, a nested [...] or {...}) up to thirty-two at a time, and members with a string-literal key and a single-token value up to sixteen at a time, so literals of thousands of such items expand within the default recursion_limit (the tests check 2,000 array items and 1,000 members). Two-token array items (a negative number) go eight at a time. Anything longer (a + b, x.len(), a member with a computed key or a longer value) costs one level of recursion per token, so a literal holds a few dozen of those at the default limit; build larger values in code.

ยงExamples

use jsonx_lib::json;

let id = 7;
let method = String::from("textDocument/hover");
let field = "line";
let msg = json!({
    "jsonrpc": "2.0",
    "id": id,
    "method": method,
    "params": { "position": { (field): 3, "character": 1 + 1 } },
    "flags": [true, null, -1.5],
});
assert_eq!(
    msg.to_string(),
    r#"{"jsonrpc":"2.0","id":7,"method":"textDocument/hover","params":{"position":{"line":3,"character":2}},"flags":[true,null,-1.5]}"#
);