rocket::serde::json

Macro json

Source
pub macro json($($json:tt)+) {
    ...
}
Available on crate feature json only.
Expand description

A macro to create ad-hoc JSON serializable values using JSON syntax.

The return type of a json! invocation is Value. A value created with this macro can be returned from a handler as follows:

use rocket::serde::json::{json, Value};

#[get("/json")]
fn get_json() -> Value {
    json!({
        "key": "value",
        "array": [1, 2, 3, 4]
    })
}

The Responder implementation for Value serializes the value into a JSON string and sets it as the body of the response with a Content-Type of application/json.

§Examples

Create a simple JSON object with two keys: "username" and "id":

use rocket::serde::json::json;

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 -->",
]);