macro_rules! json_object { () => { ... }; ($key:ident : null, $($rest:tt)*) => { ... }; ($key:ident : true, $($rest:tt)*) => { ... }; ($key:ident : false, $($rest:tt)*) => { ... }; ($key:ident : $value:expr, $($rest:tt)*) => { ... }; ([$key:expr] : $value:expr, $($rest:tt)*) => { ... }; ($key:ident, $($rest:tt)*) => { ... }; ($key:ident : $value:ident) => { ... }; ($key:ident : $value:expr) => { ... }; ([$key:expr] : $value:expr) => { ... }; ($key:ident) => { ... }; }
Expand description
Creates a static json object that can be serialized very fast.
Returns a struct implementing JSONValue.
The macro takes a comma-separated list of key-value pairs.
Keys can be written literally, or surrounded by brackets ([key])
to reference external variables. A value can be omitted, in which
case the the key name must be the name of a variable currently in scope,
from which the value will be taken.
Values must be expressions of a type implementing JSONValue.
§Examples
§Create a simple json object.
use json_in_type::*;
let my_obj = json_object!{
hello: "world"
};
assert_eq!(r#"{"hello":"world"}"#, my_obj.to_json_string());§Shorthand property names
It is common to create a json object from a set of variables, using the variable names as keys and the contents of the variables as values.
use json_in_type::*;
let x = "hello";
let y = 42;
let z = true;
let my_obj = json_object!{ x, y, z };
assert_eq!(r#"{"x":"hello","y":42,"z":true}"#, my_obj.to_json_string());§Reference external variables
use json_in_type::*;
let x = "hello";
let my_obj = json_object!{
[x]: "world", // The trailing comma is ok
};
assert_eq!(r#"{"hello":"world"}"#, my_obj.to_json_string());§Compute keys dynamically
use json_in_type::*;
let x = "hello";
let my_obj = json_object!{
[x]: "world",
[[x, "_suffix"].concat()]: 42
};
assert_eq!(r#"{"hello":"world","hello_suffix":42}"#, my_obj.to_json_string());