1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! A flexible Rust JSON library with no dependencies, no macros, no unsafe and optional `no_std` support.
//!
//! `nojson` is a flexible and ergonomic JSON library for Rust that offers a balance between the type-safety of Rust and the dynamic nature of JSON.
//! Unlike [`serde`](https://crates.io/crates/serde), which typically requires one-to-one mapping between Rust types and JSON structures (or other serialization formats),
//! `nojson` provides a toolbox approach that allows you to leverage both type-level programming and imperative code flexibility.
//!
//! ## Features
//!
//! - **No strict one-to-one type mapping required** - Mix type-level programming with imperative flexibility as needed
//! - **Clean parsing error messages** with position information for better debugging
//! - **Customizable validation** - Add application-specific validation rules with proper error context
//! - **Flexible formatting options** including pretty-printing with customizable indentation
//! - **Low-level access** to the JSON structure when needed
//! - **High-level conveniences** for common JSON operations
//! - **JSONC support** - Parse JSON with comments (`//`, `/* */`) and trailing commas
//!
//! ## Core Design Principles
//!
//! - A toolbox rather than a monolithic framework
//! - Gain the benefits of both type-level programming and imperative code
//! - Easy to add custom validations with rich error context
//! - Error messages that precisely indicate the problematic position in the JSON text
//!
//! ## Getting Started
//!
//! ### Parsing JSON with Strong Typing
//!
//! The [`Json<T>`] wrapper allows parsing JSON text into Rust types that implement `TryFrom<RawJsonValue<'_, '_>>`:
//!
//! ```
//! fn main() -> Result<(), nojson::JsonParseError> {
//! // Parse a JSON array into a typed Rust array
//! let text = "[1, null, 2]";
//! let value: nojson::Json<[Option<u32>; 3]> = text.parse()?;
//! assert_eq!(value.0, [Some(1), None, Some(2)]);
//! Ok(())
//! }
//! ```
//!
//! ### Generating JSON
//!
//! The [`DisplayJson`] trait allows converting Rust types to JSON:
//!
//! ```
//! // Generate a JSON array from a Rust array
//! let value = [Some(1), None, Some(2)];
//! assert_eq!(nojson::Json(value).to_string(), "[1,null,2]");
//! ```
//!
//! ### In-place JSON Generation with Formatting
//!
//! The [`json()`] function provides a convenient way to generate JSON with custom formatting:
//!
//! ```
//! // Compact JSON
//! let compact = nojson::json(|f| f.value([1, 2, 3]));
//! assert_eq!(compact.to_string(), "[1,2,3]");
//!
//! // Pretty-printed JSON with custom indentation
//! let pretty = nojson::json(|f| {
//! f.set_indent_size(2);
//! f.set_spacing(true);
//! f.array(|f| {
//! f.element(1)?;
//! f.element(2)?;
//! f.element(3)
//! })
//! });
//!
//! assert_eq!(
//! format!("\n{}", pretty),
//! r#"
//! [
//! 1,
//! 2,
//! 3
//! ]"#
//! );
//! ```
//!
//! ### Custom Types
//!
//! Implementing [`DisplayJson`] and `TryFrom<RawJsonValue<'_, '_>>` for your own types:
//!
//! ```
//! struct Person {
//! name: String,
//! age: u32,
//! }
//!
//! impl nojson::DisplayJson for Person {
//! fn fmt(&self, f: &mut nojson::JsonFormatter<'_, '_>) -> std::fmt::Result {
//! f.object(|f| {
//! f.member("name", &self.name)?;
//! f.member("age", self.age)
//! })
//! }
//! }
//!
//! impl<'text, 'raw> TryFrom<nojson::RawJsonValue<'text, 'raw>> for Person {
//! type Error = nojson::JsonParseError;
//!
//! fn try_from(value: nojson::RawJsonValue<'text, 'raw>) -> Result<Self, Self::Error> {
//! let name = value.to_member("name")?.required()?;
//! let age = value.to_member("age")?.required()?;
//! Ok(Person {
//! name: name.try_into()?,
//! age: age.try_into()?,
//! })
//! }
//! }
//!
//! fn main() -> Result<(), nojson::JsonParseError> {
//! // Parse JSON to Person
//! let json_text = r#"{"name":"Alice","age":30}"#;
//! let person: nojson::Json<Person> = json_text.parse()?;
//!
//! // Generate JSON from Person
//! assert_eq!(nojson::Json(&person.0).to_string(), json_text);
//!
//! Ok(())
//! }
//! ```
//!
//! ### Nested Member Access
//!
//! For simple nested lookups, you can use [`RawJsonValue::to_path_member()`]:
//!
//! ```
//! fn main() -> Result<(), nojson::JsonParseError> {
//! let json = nojson::RawJson::parse(r#"{"user":{"profile":{"name":"Alice"}}}"#)?;
//!
//! let name: String = json
//! .value()
//! .to_path_member(&["user", "profile", "name"])?
//! .required()?
//! .try_into()?;
//! let city = json
//! .value()
//! .to_path_member(&["user", "profile", "city"])?
//! .optional();
//!
//! assert_eq!(name, "Alice");
//! assert_eq!(city, None);
//! Ok(())
//! }
//! ```
//!
//! `to_path_member` is a convenience API. If you need to access multiple fields under
//! the same parent in performance-critical code, resolve the parent once and use
//! [`RawJsonValue::to_member()`] for sibling fields.
//!
//! ## Advanced Features
//!
//! ### Custom Validations
//!
//! You can add custom validations using [`RawJsonValue::invalid()`]:
//!
//! ```
//! fn parse_positive_number(text: &str) -> Result<u32, nojson::JsonParseError> {
//! let json = nojson::RawJson::parse(text)?;
//! let raw_value = json.value();
//!
//! let num: u32 = raw_value.as_number_str()?
//! .parse()
//! .map_err(|e| raw_value.invalid(e))?;
//!
//! if num == 0 {
//! return Err(raw_value.invalid("Expected a positive number, got 0"));
//! }
//!
//! Ok(num)
//! }
//! ```
//!
//! ### Error Handling with Context
//!
//! Rich error information helps with debugging:
//!
//! ```
//! let text = r#"{"invalid": 123e++}"#;
//! let result = nojson::RawJson::parse(text);
//!
//! if let Err(error) = result {
//! println!("Error: {}", error);
//!
//! // Get line and column information
//! if let Some((line, column)) = error.get_line_and_column_numbers(text) {
//! println!("At line {}, column {}", line, column);
//! }
//!
//! // Get the full line with the error
//! if let Some(line_text) = error.get_line(text) {
//! println!("Line content: {}", line_text);
//! }
//! }
//! ```
//!
//! ### JSONC Support
//!
//! Use [`RawJson::parse_jsonc()`] to parse JSON with comments and trailing commas:
//!
//! ```
//! # fn main() -> Result<(), nojson::JsonParseError> {
//! let text = r#"{
//! "name": "Alice", // line comment
//! "tags": ["a", "b",], /* trailing comma */
//! }"#;
//!
//! let (json, comment_ranges) = nojson::RawJson::parse_jsonc(text)?;
//! let name: String = json.value().to_member("name")?.required()?.try_into()?;
//! assert_eq!(name, "Alice");
//! assert_eq!(comment_ranges.len(), 2);
//! # Ok(())
//! # }
//! ```
extern crate alloc;
use ;
pub use DisplayJson;
pub use ;
pub use JsonValueKind;
pub use RawJsonMember;
pub use ;
/// A marker struct that enables JSON parsing and generation through the [`FromStr`] and [`Display`] traits.
///
/// This provides a convenient way to work with JSON, but if you need more fine-grained control,
/// consider using [`RawJson`] (for JSON parsing) and [`json()`] (for JSON generation) instead.
///
/// # Examples
///
/// Parsing JSON text:
/// ```
/// # fn main() -> Result<(), nojson::JsonParseError> {
/// // Since the `[Option<u32>; 3]` type implements `TryFrom<RawJsonValue<'_, '_>>`,
/// // you can use the `std::str::parse()` method to parse JSON by wrapping the type with `Json`.
/// let text = "[1, null, 2]";
/// let value: nojson::Json<[Option<u32>; 3]> = text.parse()?;
/// assert_eq!(value.0, [Some(1), None, Some(2)]);
/// # Ok(())
/// # }
/// ```
///
/// Generating JSON from a Rust type:
/// ```
/// # fn main() -> Result<(), nojson::JsonParseError> {
/// // Since the `[Option<u32>; 3]` type also implements the `DisplayJson` trait,
/// // you can use the `std::fmt::Display::to_string()` method to
/// // generate JSON by wrapping the type with `Json`.
/// let value = [Some(1), None, Some(2)];
/// assert_eq!(nojson::Json(value).to_string(), "[1,null,2]");
/// # Ok(())
/// # }
/// ```
] pub T);
/// Similiar to [`Json`], but can be used for pretty-printing and in-place JSON generation purposes.
///
/// # Examples
///
/// ## Basic usage
///
/// ```
/// // Standard JSON serialization (compact)
/// let compact = nojson::json(|f| f.value([1, 2, 3]));
/// assert_eq!(compact.to_string(), "[1,2,3]");
/// ```
///
/// ## Pretty printing with custom indentation
///
/// ```
/// // Pretty-printed JSON with 2-space indentation
/// let pretty = nojson::json(|f| {
/// f.set_indent_size(2);
/// f.set_spacing(true);
/// f.value([1, 2, 3])
/// });
///
/// assert_eq!(
/// format!("\n{}", pretty),
/// r#"
/// [
/// 1,
/// 2,
/// 3
/// ]"#
/// );
/// ```
///
/// ## Mixing formatting styles
///
/// ```
/// // You can nest formatters with different settings
/// let mixed = nojson::json(|f| {
/// f.set_indent_size(2);
/// f.set_spacing(true);
/// f.value([
/// &vec![1] as &dyn nojson::DisplayJson,
/// &nojson::json(|f| {
/// f.set_indent_size(0);
/// f.value(vec![2, 3])
/// }),
/// ])
/// });
///
/// assert_eq!(
/// format!("\n{}", mixed),
/// r#"
/// [
/// [
/// 1
/// ],
/// [2, 3]
/// ]"#
/// );
/// ```
+ Display
where
F: Fn ,
;
/// A convenience function for creating JSON objects.
///
/// This is shorthand for `json(|f| f.object(|f| fmt(f)))`, providing a more direct way
/// to construct JSON objects without the extra nesting.
///
/// # Examples
///
/// ```
/// let obj = nojson::object(|f| {
/// f.member("name", "Alice")?;
/// f.member("age", 30)
/// });
/// assert_eq!(obj.to_string(), r#"{"name":"Alice","age":30}"#);
/// ```
+ Display
where
F: Fn ,
/// A convenience function for creating JSON arrays.
///
/// This is shorthand for `json(|f| f.array(|f| fmt(f)))`, providing a more direct way
/// to construct JSON arrays without the extra nesting.
///
/// # Examples
///
/// ```
/// let arr = nojson::array(|f| {
/// f.element(1)?;
/// f.element(2)?;
/// f.element(3)
/// });
/// assert_eq!(arr.to_string(), "[1,2,3]");
/// ```
+ Display
where
F: Fn ,