Skip to main content

stringify_pretty

Function stringify_pretty 

Source
pub fn stringify_pretty<T: Serialize>(
    indent: usize,
    val: &T,
) -> Result<String, SerializeError<Infallible>>
Expand description

Serialize a value into a pretty-printed heap-allocated [String]. Only fails if nesting exceeds the default depth limit (32).

ยงExample

let json = nanojson::stringify_pretty(2, &[1i64, 2, 3]).unwrap();
assert_eq!(json, "[\n  1,\n  2,\n  3\n]");
Examples found in repository?
examples/big.rs (line 155)
88fn main() {
89    let mut prefs = HashMap::new();
90    prefs.insert("theme".to_string(), "dark".to_string());
91    prefs.insert("language".to_string(), "en".to_string());
92
93    let mut metadata = HashMap::new();
94    metadata.insert("warehouse".to_string(), "A1".to_string());
95    metadata.insert("currency".to_string(), "USD".to_string());
96
97    let mut sessions = HashMap::new();
98    sessions.insert("session_abc".to_string(), 1);
99    sessions.insert("session_xyz".to_string(), 2);
100
101    let state = AppState {
102        users: vec![
103            User {
104                id: 1,
105                profile: Box::new(Profile {
106                    username: "alice".to_string(),
107                    email: "alice@example.com".to_string(),
108                    address: Address {
109                        street: "Main St".to_string(),
110                        city: "Wonderland".to_string(),
111                        zip: "12345".to_string(),
112                    },
113                }),
114                roles: vec![Role::Admin, Role::User],
115                status: Status::Active,
116                tags: vec!["premium".to_string(), "beta".to_string()],
117                preferences: prefs.clone(),
118            },
119            User {
120                id: 2,
121                profile: Box::new(Profile {
122                    username: "bob".to_string(),
123                    email: "bob@example.com".to_string(),
124                    address: Address {
125                        street: "Second St".to_string(),
126                        city: "Builderland".to_string(),
127                        zip: "67890".to_string(),
128                    },
129                }),
130                roles: vec![Role::User],
131                status: Status::Pending,
132                tags: vec![],
133                preferences: prefs.clone(),
134            },
135        ],
136        inventory: Inventory {
137            items: vec![
138                Item { id: 1, name: "Sword".to_string(), price: 100 },
139                Item { id: 2, name: "Shield".to_string(), price: 150 },
140            ],
141            metadata,
142        },
143        sessions,
144        events: vec![
145            Event::Login { user_id: 1 },
146            Event::Purchase { item_id: 2, quantity: 1 },
147            Event::Logout,
148        ],
149    };
150
151    // ------------------------------------------------------------
152    // Serialize
153    // ------------------------------------------------------------
154
155    let json = nanojson::stringify_pretty(2, &state).unwrap();
156    std::println!("AppState JSON:\n{json}");
157
158    // ------------------------------------------------------------
159    // Deserialize
160    // ------------------------------------------------------------
161
162    let decoded: AppState = nanojson::parse(&json).unwrap();
163    std::println!("\nDecoded:\n{:?}", decoded);
164
165    assert_eq!(state, decoded);
166
167    // ------------------------------------------------------------
168    // Manual long JSON test (hardcoded)
169    // ------------------------------------------------------------
170
171    let raw = r#"
172    {
173        "users": [
174            {
175                "id": 3,
176                "profile": {
177                    "username": "charlie",
178                    "email": "charlie@example.com",
179                    "address": {
180                        "street": "Third St",
181                        "city": "ChocolateFactory",
182                        "zip": "99999"
183                    }
184                },
185                "roles": ["Guest"],
186                "status": "Disabled",
187                "tags": ["new"],
188                "preferences": {
189                    "theme": "light"
190                }
191            }
192        ],
193        "inventory": {
194            "items": [
195                { "id": 10, "name": "Potion", "price": 50 }
196            ],
197            "metadata": {
198                "warehouse": "B2"
199            }
200        },
201        "sessions": {
202            "session_foo": 3
203        },
204        "events": [
205            { "Login": { "user_id": 3 } },
206            { "Logout": null }
207        ]
208    }
209    "#;
210
211    println!("");
212    match nanojson::parse::<AppState>(raw) {
213        Ok(parsed) => {
214            std::println!("\nParsed from raw JSON:\n{:?}", parsed);
215        }
216        Err(e) =>  e.print(raw),
217    }
218}
More examples
Hide additional examples
examples/medium.rs (line 160)
73fn main() {
74    let forum = Forum {
75        threads: vec![
76            Thread {
77                name: "General".to_string(),
78                posts: vec![
79                    Post {
80                        id: 1,
81                        title: "Welcome".to_string(),
82                        body: "Welcome to the forum!".to_string(),
83                        comments: vec![
84                            Comment {
85                                user: "alice".to_string(),
86                                message: "Nice to be here!".to_string(),
87                            },
88                            Comment {
89                                user: "bob".to_string(),
90                                message: "Hello everyone!".to_string(),
91                            },
92                        ],
93                    },
94                    Post {
95                        id: 2,
96                        title: "Rules".to_string(),
97                        body: "Be nice.".to_string(),
98                        comments: vec![],
99                    },
100                ],
101            },
102            Thread {
103                name: "Rust".to_string(),
104                posts: vec![
105                    Post {
106                        id: 3,
107                        title: "Ownership".to_string(),
108                        body: "Let's discuss ownership.".to_string(),
109                        comments: vec![
110                            Comment {
111                                user: "charlie".to_string(),
112                                message: "It's tricky at first.".to_string(),
113                            }
114                        ],
115                    }
116                ],
117            }
118        ],
119
120        activity_feed: vec![
121            Activity::View { post_id: 1 },
122            Activity::React { post_id: 1, reaction: Reaction::Like },
123            Activity::Comment { post_id: 2, message: "Important!".to_string() },
124        ],
125
126        category_tree: Box::new(Node {
127            value: "root".to_string(),
128            children: vec![
129                Box::new(Node {
130                    value: "programming".to_string(),
131                    children: vec![
132                        Box::new(Node {
133                            value: "rust".to_string(),
134                            children: vec![],
135                        }),
136                        Box::new(Node {
137                            value: "c++".to_string(),
138                            children: vec![],
139                        }),
140                    ],
141                }),
142                Box::new(Node {
143                    value: "offtopic".to_string(),
144                    children: vec![],
145                }),
146            ],
147        }),
148
149        tags: vec![
150            vec!["rust".to_string(), "systems".to_string()],
151            vec!["fun".to_string()],
152            vec![],
153        ],
154    };
155
156    // ------------------------------------------------------------
157    // Serialize
158    // ------------------------------------------------------------
159
160    let json = nanojson::stringify_pretty(2, &forum).unwrap();
161    std::println!("Forum JSON:\n{json}");
162
163    // ------------------------------------------------------------
164    // Deserialize
165    // ------------------------------------------------------------
166
167    let decoded: Forum = nanojson::parse(&json).unwrap();
168    std::println!("\nDecoded:\n{:?}", decoded);
169
170    assert_eq!(forum, decoded);
171
172    // ------------------------------------------------------------
173    // Hardcoded JSON test
174    // ------------------------------------------------------------
175
176    let raw = r#"
177    {
178        "threads": [
179            {
180                "name": "Announcements",
181                "posts": [
182                    {
183                        "id": 10,
184                        "title": "Update",
185                        "body": "New features added",
186                        "comments": [
187                            { "user": "admin", "message": "Enjoy!" }
188                        ]
189                    }
190                ]
191            }
192        ],
193        "activity_feed": [
194            { "View": { "post_id": 10 } },
195            { "React": { "post_id": 10, "reaction": "Laugh" } }
196        ],
197        "category_tree": {
198            "value": "root",
199            "children": []
200        },
201        "tags": [
202            ["news"],
203            []
204        ]
205    }
206    "#;
207
208    println!("");
209    match nanojson::parse::<Forum>(raw) {
210        Ok(parsed) => {
211            std::println!("\nParsed from raw JSON:\n{:?}", parsed);
212        }
213        Err(e) =>  e.print(raw),
214    }
215}