value-ext 0.1.4

Serde Json Value Extension Trait and Json Utilities
Documentation
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
422
423
424
425
426
427
use crate::AsType;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Map, Value, json};
use std::collections::VecDeque;

/// Extension trait for working with JSON values in a more convenient way.
///
/// `JsonValueExt` offers convenient methods for interacting with `serde_json::Value` objects,
/// simplifying tasks like getting, taking, inserting, traversing, and pretty-printing JSON data
/// while ensuring type safety with Serde's serialization and deserialization.
///
/// # Provided Methods
///
/// - **`x_get`**: Returns an owned value of a specified type `T` from a JSON object using either a direct name or a pointer path.
/// - **`x_get_as`**: Returns a reference of a specified type `T` from a JSON object using either a direct name or a pointer path.
/// - **`x_get_str`**: Returns a `&str` from a JSON object using either a direct name or a pointer path.
/// - **`x_get_i64`**: Returns an `i64` from a JSON object using either a direct name or a pointer path.
/// - **`x_get_f64`**: Returns an `f64` from a JSON object using either a direct name or a pointer path.
/// - **`x_get_bool`**: Returns a `bool` from a JSON object using either a direct name or a pointer path.
/// - **`x_get_strs`**: Returns a `Vec<&str>` from a JSON array using either a direct name or a pointer path.
/// - **`x_get_i64s`**: Returns a `Vec<i64>` from a JSON array using either a direct name or a pointer path.
/// - **`x_get_f64s`**: Returns a `Vec<f64>` from a JSON array using either a direct name or a pointer path.
/// - **`x_get_bools`**: Returns a `Vec<bool>` from a JSON array using either a direct name or a pointer path.
/// - **`x_get_object`**: Returns a reference to the object map at the specified name or pointer path.
/// - **`x_take`**: Takes a value from a JSON object using a specified name or pointer path, replacing it with `Null`.
/// - **`x_remove`**: Removes the value at the specified name or pointer path from the JSON object and returns it,
///   leaving no placeholder in the object (unlike `x_take`).
/// - **`x_insert`**: Inserts a new value of type `T` into a JSON object at the specified name or pointer path,
///   creating any missing objects along the way.
/// - **`x_walk`**: Traverses all properties in the JSON value tree and calls the callback function on each.
/// - **`x_pretty`**: Returns a pretty-printed string representation of the JSON value.
pub trait JsonValueExt {
	fn x_new_object() -> Value;

	fn x_contains<T: DeserializeOwned>(&self, name_or_pointer: &str) -> bool;

	/// Returns an owned type `T` for a given name or pointer path.
	/// Note: This will create a clone of the matched Value.
	/// - `name_or_pointer`: Can be a direct name or a pointer path (if it starts with '/').
	fn x_get<T: DeserializeOwned>(&self, name_or_pointer: &str) -> Result<T>;

	/// Returns a reference of type `T` (or a copy for copy types) for a given name or pointer path.
	/// Use this one over `x_get` to avoid string allocation.
	/// - `name_or_pointer`: Can be a direct name or a pointer path (if it starts with '/').
	fn x_get_as<'a, T: AsType<'a>>(&'a self, name_or_pointer: &str) -> Result<T>;

	/// Returns a &str if present (shortcut for `x_get_as::<&str>(...)`)
	fn x_get_str(&self, name_or_pointer: &str) -> Result<&str> {
		self.x_get_as(name_or_pointer)
	}

	/// Returns an i64 if present (shortcut for `x_get_as::<i64>(...)`)
	fn x_get_i64(&self, name_or_pointer: &str) -> Result<i64> {
		self.x_get_as(name_or_pointer)
	}

	/// Returns an f64 if present (shortcut for `x_get_as::<f64>(...)`)
	fn x_get_f64(&self, name_or_pointer: &str) -> Result<f64> {
		self.x_get_as(name_or_pointer)
	}

	/// Returns a bool if present (shortcut for `x_get_as::<bool>(...)`)
	fn x_get_bool(&self, name_or_pointer: &str) -> Result<bool> {
		self.x_get_as(name_or_pointer)
	}

	/// Returns a Vec<&str> if present (shortcut for `x_get_as::<Vec<&str>>(...)`)
	fn x_get_strs(&self, name_or_pointer: &str) -> Result<Vec<&str>> {
		self.x_get_as(name_or_pointer)
	}

	/// Returns a Vec<i64> if present (shortcut for `x_get_as::<Vec<i64>>(...)`)
	fn x_get_i64s(&self, name_or_pointer: &str) -> Result<Vec<i64>> {
		self.x_get_as(name_or_pointer)
	}

	/// Returns a Vec<f64> if present (shortcut for `x_get_as::<Vec<f64>>(...)`)
	fn x_get_f64s(&self, name_or_pointer: &str) -> Result<Vec<f64>> {
		self.x_get_as(name_or_pointer)
	}

	/// Returns a Vec<bool> if present (shortcut for `x_get_as::<Vec<bool>>(...)`)
	fn x_get_bools(&self, name_or_pointer: &str) -> Result<Vec<bool>> {
		self.x_get_as(name_or_pointer)
	}

	/// Returns a reference to the object map at the given name or pointer path.
	/// - `name_or_pointer`: Can be a direct name or a pointer path (if it starts with '/').
	fn x_get_object(&self, name_or_pointer: &str) -> Result<&serde_json::Map<String, Value>>;

	/// Takes the value at the specified name or pointer path and replaces it with `Null`.
	/// - `name_or_pointer`: Can be a direct name or a pointer path (if it starts with '/').
	fn x_take<T: DeserializeOwned>(&mut self, name_or_pointer: &str) -> Result<T>;

	/// Removes the value at the specified name or pointer path from the JSON object
	/// and returns it without leaving a placeholder, unlike `x_take`.
	fn x_remove<T: DeserializeOwned>(&mut self, name_or_pointer: &str) -> Result<T>;

	/// Inserts a new value of type `T` at the specified name or pointer path.
	/// This method creates missing `Value::Object` entries as needed.
	/// - `name_or_pointer`: Can be a direct name or a pointer path (if it starts with '/').
	fn x_insert<T: Serialize>(&mut self, name_or_pointer: &str, value: T) -> Result<()>;

	/// Merges another JSON object into this one (shallow merge).
	/// - If `self` is not an Object, returns error.
	/// - If `other` is Null, does nothing.
	/// - If `other` is not an Object, returns error.
	fn x_merge(&mut self, other: Value) -> Result<()>;

	/// Walks through all properties in the JSON value tree and calls the callback function on each.
	/// - The callback signature is `(parent_map, property_name) -> bool`.
	///   - Returns `false` to stop the traversal; returns `true` to continue.
	///
	/// Returns:
	/// - `true` if the traversal completes without stopping early.
	/// - `false` if the traversal was stopped early because the callback returned `false`.
	fn x_walk<F>(&mut self, callback: F) -> bool
	where
		F: FnMut(&mut Map<String, Value>, &str) -> bool;

	/// Returns a pretty-printed string representation of the JSON value.
	fn x_pretty(&self) -> Result<String>;
}

impl JsonValueExt for Value {
	fn x_new_object() -> Value {
		Value::Object(Map::new())
	}

	fn x_contains<T: DeserializeOwned>(&self, name_or_pointer: &str) -> bool {
		if name_or_pointer.starts_with('/') {
			self.pointer(name_or_pointer).is_some()
		} else {
			self.get(name_or_pointer).is_some()
		}
	}

	fn x_get<T: DeserializeOwned>(&self, name_or_pointer: &str) -> Result<T> {
		let value = if name_or_pointer.starts_with('/') {
			self.pointer(name_or_pointer)
				.ok_or_else(|| JsonValueExtError::PropertyNotFound(name_or_pointer.to_string()))?
		} else {
			self.get(name_or_pointer)
				.ok_or_else(|| JsonValueExtError::PropertyNotFound(name_or_pointer.to_string()))?
		};

		let value: T =
			serde_json::from_value(value.clone())
				.map_err(JsonValueExtError::from)
				.map_err(|err| match err {
					JsonValueExtError::ValueNotOfType(not_of_type) => JsonValueExtError::PropertyValueNotOfType {
						name: name_or_pointer.to_string(),
						not_of_type,
					},
					other => other,
				})?;

		Ok(value)
	}

	fn x_get_object(&self, name_or_pointer: &str) -> Result<&serde_json::Map<String, Value>> {
		let value = if name_or_pointer.starts_with('/') {
			self.pointer(name_or_pointer)
				.ok_or_else(|| JsonValueExtError::PropertyNotFound(name_or_pointer.to_string()))?
		} else {
			self.get(name_or_pointer)
				.ok_or_else(|| JsonValueExtError::PropertyNotFound(name_or_pointer.to_string()))?
		};

		value.as_object().ok_or_else(|| JsonValueExtError::PropertyValueNotOfType {
			name: name_or_pointer.to_string(),
			not_of_type: "Object",
		})
	}

	fn x_get_as<'a, T: AsType<'a>>(&'a self, name_or_pointer: &str) -> Result<T> {
		let value = if name_or_pointer.starts_with('/') {
			self.pointer(name_or_pointer)
				.ok_or_else(|| JsonValueExtError::PropertyNotFound(name_or_pointer.to_string()))?
		} else {
			self.get(name_or_pointer)
				.ok_or_else(|| JsonValueExtError::PropertyNotFound(name_or_pointer.to_string()))?
		};

		T::from_value(value).map_err(|err| match err {
			JsonValueExtError::ValueNotOfType(not_of_type) => JsonValueExtError::PropertyValueNotOfType {
				name: name_or_pointer.to_string(),
				not_of_type,
			},
			other => other,
		})
	}

	fn x_take<T: DeserializeOwned>(&mut self, name_or_pointer: &str) -> Result<T> {
		let value = if name_or_pointer.starts_with('/') {
			self.pointer_mut(name_or_pointer)
				.map(Value::take)
				.ok_or_else(|| JsonValueExtError::PropertyNotFound(name_or_pointer.to_string()))?
		} else {
			self.get_mut(name_or_pointer)
				.map(Value::take)
				.ok_or_else(|| JsonValueExtError::PropertyNotFound(name_or_pointer.to_string()))?
		};

		let value: T = serde_json::from_value(value)?;
		Ok(value)
	}

	fn x_remove<T: DeserializeOwned>(&mut self, name_or_pointer: &str) -> Result<T> {
		if !name_or_pointer.starts_with('/') {
			match self {
				Value::Object(map) => {
					let removed = map
						.remove(name_or_pointer)
						.ok_or_else(|| JsonValueExtError::PropertyNotFound(name_or_pointer.to_string()))?;
					let value: T = serde_json::from_value(removed)?;
					Ok(value)
				}
				_ => Err(JsonValueExtError::custom("Value is not an Object; cannot x_remove")),
			}
		} else {
			let parts: Vec<&str> = name_or_pointer.split('/').skip(1).collect();
			if parts.is_empty() {
				return Err(JsonValueExtError::custom("Invalid path"));
			}
			let mut current = self;
			for &part in &parts[..parts.len() - 1] {
				match current {
					Value::Object(map) => {
						current = map
							.get_mut(part)
							.ok_or_else(|| JsonValueExtError::PropertyNotFound(name_or_pointer.to_string()))?;
					}
					Value::Array(arr) => {
						let index: usize = part
							.parse()
							.map_err(|_| JsonValueExtError::custom("Invalid array index in pointer"))?;
						if index < arr.len() {
							current = &mut arr[index];
						} else {
							return Err(JsonValueExtError::PropertyNotFound(name_or_pointer.to_string()));
						}
					}
					_ => return Err(JsonValueExtError::custom("Path does not point to an Object or Array")),
				}
			}
			let last_part = parts
				.last()
				.ok_or_else(|| JsonValueExtError::custom("Last element not found"))?;
			match current {
				Value::Object(map) => {
					let removed = map
						.remove(*last_part)
						.ok_or_else(|| JsonValueExtError::PropertyNotFound(name_or_pointer.to_string()))?;
					let value: T = serde_json::from_value(removed)?;
					Ok(value)
				}
				Value::Array(arr) => {
					let index: usize = last_part
						.parse()
						.map_err(|_| JsonValueExtError::custom("Invalid array index in pointer"))?;
					if index < arr.len() {
						let removed = arr.remove(index);
						let value: T = serde_json::from_value(removed)?;
						Ok(value)
					} else {
						Err(JsonValueExtError::PropertyNotFound(name_or_pointer.to_string()))
					}
				}
				_ => Err(JsonValueExtError::custom("Path does not point to an Object or Array")),
			}
		}
	}

	fn x_insert<T: Serialize>(&mut self, name_or_pointer: &str, value: T) -> Result<()> {
		let new_value = serde_json::to_value(value)?;

		if !name_or_pointer.starts_with('/') {
			match self {
				Value::Object(map) => {
					map.insert(name_or_pointer.to_string(), new_value);
					Ok(())
				}
				_ => Err(JsonValueExtError::custom("Value is not an Object; cannot x_insert")),
			}
		} else {
			let parts: Vec<&str> = name_or_pointer.split('/').skip(1).collect();
			let mut current = self;

			// -- Add the eventual missing parents
			for &part in &parts[..parts.len() - 1] {
				match current {
					Value::Object(map) => {
						current = map.entry(part).or_insert_with(|| json!({}));
					}
					_ => return Err(JsonValueExtError::custom("Path does not point to an Object")),
				}
			}

			// -- Set the value at the last element
			if let Some(&last_part) = parts.last() {
				match current {
					Value::Object(map) => {
						map.insert(last_part.to_string(), new_value);
						Ok(())
					}
					_ => Err(JsonValueExtError::custom("Path does not point to an Object")),
				}
			} else {
				Err(JsonValueExtError::custom("Invalid path"))
			}
		}
	}

	fn x_merge(&mut self, other: Value) -> Result<()> {
		if other.is_null() {
			return Ok(());
		}

		let other_map = match other {
			Value::Object(map) => map,
			_ => {
				return Err(JsonValueExtError::custom(
					"Other value is not an Object; cannot x_merge",
				));
			}
		};

		match self {
			Value::Object(map) => {
				map.extend(other_map);
				Ok(())
			}
			_ => Err(JsonValueExtError::custom("Value is not an Object; cannot x_merge")),
		}
	}

	fn x_pretty(&self) -> Result<String> {
		let content = serde_json::to_string_pretty(self)?;
		Ok(content)
	}

	/// Walks through all properties of a JSON value tree and calls the callback function on each property.
	///
	/// - The callback signature is `(parent_map, property_name) -> bool`.
	///   - Return `false` from the callback to stop the traversal; return `true` to continue.
	///
	/// Returns:
	/// - `true` if the traversal completed to the end without being stopped early.
	/// - `false` if the traversal was stopped early because the callback returned `false`.
	fn x_walk<F>(&mut self, mut callback: F) -> bool
	where
		F: FnMut(&mut Map<String, Value>, &str) -> bool,
	{
		let mut queue = VecDeque::new();
		queue.push_back(self);

		while let Some(current) = queue.pop_front() {
			if let Value::Object(map) = current {
				// Call the callback for each property name in the current map
				for key in map.keys().cloned().collect::<Vec<_>>() {
					let res = callback(map, &key);
					if !res {
						return false;
					}
				}

				// Add all nested objects and arrays to the queue for further processing
				for value in map.values_mut() {
					if value.is_object() || value.is_array() {
						queue.push_back(value);
					}
				}
			} else if let Value::Array(arr) = current {
				// If the current value is an array, add its elements to the queue
				for value in arr.iter_mut() {
					if value.is_object() || value.is_array() {
						queue.push_back(value);
					}
				}
			}
		}
		true
	}
}

// region:    --- Error
type Result<T> = core::result::Result<T, JsonValueExtError>;

#[derive(Debug, derive_more::From)]
pub enum JsonValueExtError {
	Custom(String),

	PropertyNotFound(String),

	PropertyValueNotOfType {
		name: String,
		not_of_type: &'static str,
	},

	// -- AsType errors
	ValueNotOfType(&'static str),

	#[from]
	SerdeJson(serde_json::Error),
}

impl JsonValueExtError {
	pub(crate) fn custom(val: impl std::fmt::Display) -> Self {
		Self::Custom(val.to_string())
	}
}

// region:    --- Error Boilerplate

impl core::fmt::Display for JsonValueExtError {
	fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::result::Result<(), core::fmt::Error> {
		write!(fmt, "{self:?}")
	}
}

impl std::error::Error for JsonValueExtError {}

// endregion: --- Error Boilerplate

// endregion: --- Error