Macro rocket_contrib::json [−][src]
macro_rules! json { ($($json:tt)+) => { ... }; }
A macro to create ad-hoc JSON serializable values using JSON syntax.
Usage
To import the macro, add the #[macro_use]
attribute to the extern crate rocket_contrib
invocation:
#[macro_use] extern crate rocket_contrib;
The return type of a macro invocation is
Value
. This is the default type for the
type parameter of Json
and as such,
you can return Json
without specifying the type using a json!
value for
Json
. A value created with this macro can be returned from a handler as
follows:
use rocket_contrib::Json; #[get("/json")] fn get_json() -> Json { Json(json!({ "key": "value", "array": [1, 2, 3, 4] })) }
Examples
Create a simple JSON object with two keys: "username"
and "id"
:
let value = json!({ "username": "mjordan", "id": 23 });
Create a more complex object with a nested object and array:
let value = json!({ "code": 200, "success": true, "payload": { "features": ["serde", "json"], "ids": [12, 121], }, });
Variables or expressions can be interpolated into the JSON literal. Any type
interpolated into an array element or object value must implement Serde's
Serialize
trait, while any type interpolated into a object key must
implement Into<String>
.
let code = 200; let features = vec!["serde", "json"]; let value = json!({ "code": code, "success": code == 200, "payload": { features[0]: features[1] } });
Trailing commas are allowed inside both arrays and objects.
let value = json!([ "notice", "the", "trailing", "comma -->", ]);