Skip to main content

Module json_format

Module json_format 

Source
Expand description

JSON-backed Debug and Display writers and the macros that wire a type to them. JSON-backed Debug and Display implementations.

Many result and strategy types format themselves as their own JSON: Display writes the compact form ({"a":1}) and Debug the indented one. The two writers below are the only implementation of that convention, and impl_json_display!, impl_json_debug! and impl_json_debug_pretty! wire a type to them. They replace the pretty-simple-display derive macros, so no crate of the workspace depends on a formatting crate to print its types (M6-05, #546).

A value that fails to serialize does not abort formatting: the writers print Error serializing to JSON: <reason> in place of the JSON, so to_string() and {:?} never panic on such a value.

use optionstratlib_core::{impl_json_debug_pretty, impl_json_display};
use serde::Serialize;

#[derive(Serialize)]
struct Quote {
    bid: u32,
    ask: u32,
}
impl_json_display!(Quote);
impl_json_debug_pretty!(Quote);

let quote = Quote { bid: 1, ask: 2 };
assert_eq!(quote.to_string(), r#"{"bid":1,"ask":2}"#);
assert_eq!(format!("{quote:?}"), "{\n  \"bid\": 1,\n  \"ask\": 2\n}");

Functionsยง

write_json
Writes value to f as compact JSON.
write_json_pretty
Writes value to f as indented JSON (two spaces per level).