imbl_value/lib.rs
1use imbl::Vector;
2use index::Index;
3use serde::{de::DeserializeOwned, Serialize};
4
5use std::{
6 fmt::{self, Debug, Display},
7 io,
8 sync::Arc,
9};
10
11pub mod de;
12pub mod in_order_map;
13pub mod index;
14pub mod macros;
15pub mod ser;
16#[cfg(feature = "treediff")]
17pub mod treediff;
18
19pub use imbl;
20pub use in_order_map::InOMap;
21pub use serde_json::Error as ErrorSource;
22pub use serde_json::Number;
23pub use yasi::InternedString;
24
25pub const NULL: Value = Value::Null;
26
27#[derive(Debug)]
28pub enum ErrorKind {
29 Serialization,
30 Deserialization,
31}
32
33#[derive(Debug)]
34pub struct Error {
35 pub kind: ErrorKind,
36 pub source: ErrorSource,
37}
38impl std::fmt::Display for Error {
39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40 write!(f, "{:?} Error: {}", self.kind, self.source)
41 }
42}
43impl std::error::Error for Error {}
44
45/// See the [`serde_json::value` module documentation](self) for usage examples.
46#[derive(Clone)]
47pub enum Value {
48 /// Represents a JSON null value.
49 ///
50 /// ```
51 /// # use serde_json::json;
52 /// #
53 /// let v = json!(null);
54 /// ```
55 Null,
56
57 /// Represents a JSON boolean.
58 ///
59 /// ```
60 /// # use serde_json::json;
61 /// #
62 /// let v = json!(true);
63 /// ```
64 Bool(bool),
65
66 /// Represents a JSON number, whether integer or floating point.
67 ///
68 /// ```
69 /// # use serde_json::json;
70 /// #
71 /// let v = json!(12.5);
72 /// ```
73 Number(Number),
74
75 /// Represents a JSON string.
76 ///
77 /// ```
78 /// # use serde_json::json;
79 /// #
80 /// let v = json!("a string");
81 /// ```
82 String(Arc<String>),
83
84 /// Represents a JSON array.
85 ///
86 /// ```
87 /// # use serde_json::json;
88 /// #
89 /// let v = json!(["an", "array"]);
90 /// ```
91 Array(Vector<Value>),
92
93 /// Represents a JSON object.
94 ///
95 /// By default the map is backed by a BTreeMap. Enable the `preserve_order`
96 /// feature of serde_json to use IndexMap instead, which preserves
97 /// entries in the order they are inserted into the map. In particular, this
98 /// allows JSON data to be deserialized into a Value and serialized to a
99 /// string while retaining the order of map keys in the input.
100 ///
101 /// ```
102 /// # use serde_json::json;
103 /// #
104 /// let v = json!({ "an": "object" });
105 /// ```
106 Object(InOMap<InternedString, Value>),
107}
108
109impl Debug for Value {
110 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
111 match self {
112 Value::Null => formatter.write_str("Null"),
113 Value::Bool(boolean) => write!(formatter, "Bool({})", boolean),
114 Value::Number(number) => Debug::fmt(number, formatter),
115 Value::String(string) => write!(formatter, "String({:?})", string),
116 Value::Array(vec) => {
117 formatter.write_str("Array ")?;
118 Debug::fmt(vec, formatter)
119 }
120 Value::Object(map) => {
121 formatter.write_str("Object ")?;
122 Debug::fmt(map, formatter)
123 }
124 }
125 }
126}
127
128impl Display for Value {
129 /// Display a JSON value as a string.
130 ///
131 /// ```
132 /// # use serde_json::json;
133 /// #
134 /// let json = json!({ "city": "London", "street": "10 Downing Street" });
135 ///
136 /// // Compact format:
137 /// //
138 /// // {"city":"London","street":"10 Downing Street"}
139 /// let compact = format!("{}", json);
140 /// assert_eq!(compact,
141 /// "{\"city\":\"London\",\"street\":\"10 Downing Street\"}");
142 ///
143 /// // Pretty format:
144 /// //
145 /// // {
146 /// // "city": "London",
147 /// // "street": "10 Downing Street"
148 /// // }
149 /// let pretty = format!("{:#}", json);
150 /// assert_eq!(pretty,
151 /// "{\n \"city\": \"London\",\n \"street\": \"10 Downing Street\"\n}");
152 /// ```
153 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
154 struct WriterFormatter<'a, 'b: 'a> {
155 inner: &'a mut fmt::Formatter<'b>,
156 }
157
158 impl<'a, 'b> io::Write for WriterFormatter<'a, 'b> {
159 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
160 // Safety: the serializer below only emits valid utf8 when using
161 // the default formatter.
162 let s = unsafe { String::from_utf8_unchecked(buf.to_owned()) };
163 self.inner.write_str(&s).map_err(io_error)?;
164 Ok(buf.len())
165 }
166
167 fn flush(&mut self) -> io::Result<()> {
168 Ok(())
169 }
170 }
171
172 fn io_error(_: fmt::Error) -> io::Error {
173 // Error value does not matter because Display impl just maps it
174 // back to fmt::Error.
175 io::Error::new(io::ErrorKind::Other, "fmt error")
176 }
177
178 let alternate = f.alternate();
179 let mut wr = WriterFormatter { inner: f };
180 if alternate {
181 // {:#}
182 serde_json::ser::to_writer_pretty(&mut wr, self).map_err(|_| fmt::Error)
183 } else {
184 // {}
185 serde_json::ser::to_writer(&mut wr, self).map_err(|_| fmt::Error)
186 }
187 }
188}
189
190impl From<serde_json::Value> for Value {
191 fn from(value: serde_json::Value) -> Self {
192 match value {
193 serde_json::Value::Array(a) => Self::Array(a.into_iter().map(|a| a.into()).collect()),
194 serde_json::Value::Bool(a) => Self::Bool(a),
195 serde_json::Value::Null => Self::Null,
196 serde_json::Value::Number(a) => Self::Number(a),
197 serde_json::Value::Object(a) => {
198 Self::Object(a.into_iter().map(|(a, b)| (a.into(), b.into())).collect())
199 }
200 serde_json::Value::String(a) => Self::String(a.into()),
201 }
202 }
203}
204
205impl From<Value> for serde_json::Value {
206 fn from(value: Value) -> Self {
207 match value {
208 Value::Array(a) => Self::Array(a.into_iter().map(|a| a.into()).collect()),
209 Value::Bool(a) => Self::Bool(a),
210 Value::Null => Self::Null,
211 Value::Number(a) => Self::Number(a),
212 Value::Object(a) => Self::Object(
213 a.into_iter()
214 .map(|(a, b)| ((&*a).to_owned(), b.into()))
215 .collect(),
216 ),
217 Value::String(a) => Self::String((&*a).to_owned()),
218 }
219 }
220}
221
222fn parse_index(s: &str) -> Option<usize> {
223 if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) {
224 return None;
225 }
226 s.parse().ok()
227}
228
229impl Value {
230 /// Index into a JSON array or map. A string index can be used to access a
231 /// value in a map, and a usize index can be used to access an element of an
232 /// array.
233 ///
234 /// Returns `None` if the type of `self` does not match the type of the
235 /// index, for example if the index is a string and `self` is an array or a
236 /// number. Also returns `None` if the given key does not exist in the map
237 /// or the given index is not within the bounds of the array.
238 ///
239 /// ```
240 /// # use serde_json::json;
241 /// #
242 /// let object = json!({ "A": 65, "B": 66, "C": 67 });
243 /// assert_eq!(*object.get("A").unwrap(), json!(65));
244 ///
245 /// let array = json!([ "A", "B", "C" ]);
246 /// assert_eq!(*array.get(2).unwrap(), json!("C"));
247 ///
248 /// assert_eq!(array.get("A"), None);
249 /// ```
250 ///
251 /// Square brackets can also be used to index into a value in a more concise
252 /// way. This returns `Value::Null` in cases where `get` would have returned
253 /// `None`.
254 ///
255 /// ```
256 /// # use serde_json::json;
257 /// #
258 /// let object = json!({
259 /// "A": ["a", "á", "à"],
260 /// "B": ["b", "b́"],
261 /// "C": ["c", "ć", "ć̣", "ḉ"],
262 /// });
263 /// assert_eq!(object["B"][0], json!("b"));
264 ///
265 /// assert_eq!(object["D"], json!(null));
266 /// assert_eq!(object[0]["x"]["y"]["z"], json!(null));
267 /// ```
268 pub fn get<I: Index>(&self, index: I) -> Option<&Value> {
269 index.index_into(self)
270 }
271
272 /// Mutably index into a JSON array or map. A string index can be used to
273 /// access a value in a map, and a usize index can be used to access an
274 /// element of an array.
275 ///
276 /// Returns `None` if the type of `self` does not match the type of the
277 /// index, for example if the index is a string and `self` is an array or a
278 /// number. Also returns `None` if the given key does not exist in the map
279 /// or the given index is not within the bounds of the array.
280 ///
281 /// ```
282 /// # use serde_json::json;
283 /// #
284 /// let mut object = json!({ "A": 65, "B": 66, "C": 67 });
285 /// *object.get_mut("A").unwrap() = json!(69);
286 ///
287 /// let mut array = json!([ "A", "B", "C" ]);
288 /// *array.get_mut(2).unwrap() = json!("D");
289 /// ```
290 pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Value> {
291 index.index_into_mut(self)
292 }
293
294 /// Returns true if the `Value` is an Object. Returns false otherwise.
295 ///
296 /// For any Value on which `is_object` returns true, `as_object` and
297 /// `as_object_mut` are guaranteed to return the map representation of the
298 /// object.
299 ///
300 /// ```
301 /// # use serde_json::json;
302 /// #
303 /// let obj = json!({ "a": { "nested": true }, "b": ["an", "array"] });
304 ///
305 /// assert!(obj.is_object());
306 /// assert!(obj["a"].is_object());
307 ///
308 /// // array, not an object
309 /// assert!(!obj["b"].is_object());
310 /// ```
311 pub fn is_object(&self) -> bool {
312 self.as_object().is_some()
313 }
314
315 /// If the `Value` is an Object, returns the associated Map. Returns None
316 /// otherwise.
317 ///
318 /// ```
319 /// # use serde_json::json;
320 /// #
321 /// let v = json!({ "a": { "nested": true }, "b": ["an", "array"] });
322 ///
323 /// // The length of `{"nested": true}` is 1 entry.
324 /// assert_eq!(v["a"].as_object().unwrap().len(), 1);
325 ///
326 /// // The array `["an", "array"]` is not an object.
327 /// assert_eq!(v["b"].as_object(), None);
328 /// ```
329 pub fn as_object(&self) -> Option<&InOMap<InternedString, Value>> {
330 match self {
331 Value::Object(map) => Some(map),
332 _ => None,
333 }
334 }
335
336 /// If the `Value` is an Object, returns the associated mutable Map.
337 /// Returns None otherwise.
338 ///
339 /// ```
340 /// # use serde_json::json;
341 /// #
342 /// let mut v = json!({ "a": { "nested": true } });
343 ///
344 /// v["a"].as_object_mut().unwrap().clear();
345 /// assert_eq!(v, json!({ "a": {} }));
346 /// ```
347 pub fn as_object_mut(&mut self) -> Option<&mut InOMap<InternedString, Value>> {
348 match self {
349 Value::Object(map) => Some(map),
350 _ => None,
351 }
352 }
353
354 /// Returns true if the `Value` is an Array. Returns false otherwise.
355 ///
356 /// For any Value on which `is_array` returns true, `as_array` and
357 /// `as_array_mut` are guaranteed to return the vector representing the
358 /// array.
359 ///
360 /// ```
361 /// # use serde_json::json;
362 /// #
363 /// let obj = json!({ "a": ["an", "array"], "b": { "an": "object" } });
364 ///
365 /// assert!(obj["a"].is_array());
366 ///
367 /// // an object, not an array
368 /// assert!(!obj["b"].is_array());
369 /// ```
370 pub fn is_array(&self) -> bool {
371 self.as_array().is_some()
372 }
373
374 /// If the `Value` is an Array, returns the associated vector. Returns None
375 /// otherwise.
376 ///
377 /// ```
378 /// # use serde_json::json;
379 /// #
380 /// let v = json!({ "a": ["an", "array"], "b": { "an": "object" } });
381 ///
382 /// // The length of `["an", "array"]` is 2 elements.
383 /// assert_eq!(v["a"].as_array().unwrap().len(), 2);
384 ///
385 /// // The object `{"an": "object"}` is not an array.
386 /// assert_eq!(v["b"].as_array(), None);
387 /// ```
388 pub fn as_array(&self) -> Option<&Vector<Value>> {
389 match self {
390 Value::Array(array) => Some(array),
391 _ => None,
392 }
393 }
394
395 /// If the `Value` is an Array, returns the associated mutable vector.
396 /// Returns None otherwise.
397 ///
398 /// ```
399 /// # use serde_json::json;
400 /// #
401 /// let mut v = json!({ "a": ["an", "array"] });
402 ///
403 /// v["a"].as_array_mut().unwrap().clear();
404 /// assert_eq!(v, json!({ "a": [] }));
405 /// ```
406 pub fn as_array_mut(&mut self) -> Option<&mut Vector<Value>> {
407 match self {
408 Value::Array(list) => Some(list),
409 _ => None,
410 }
411 }
412
413 /// Returns true if the `Value` is a String. Returns false otherwise.
414 ///
415 /// For any Value on which `is_string` returns true, `as_str` is guaranteed
416 /// to return the string slice.
417 ///
418 /// ```
419 /// # use serde_json::json;
420 /// #
421 /// let v = json!({ "a": "some string", "b": false });
422 ///
423 /// assert!(v["a"].is_string());
424 ///
425 /// // The boolean `false` is not a string.
426 /// assert!(!v["b"].is_string());
427 /// ```
428 pub fn is_string(&self) -> bool {
429 self.as_str().is_some()
430 }
431
432 /// If the `Value` is a String, returns the associated str. Returns None
433 /// otherwise.
434 ///
435 /// ```
436 /// # use serde_json::json;
437 /// #
438 /// let v = json!({ "a": "some string", "b": false });
439 ///
440 /// assert_eq!(v["a"].as_str(), Some("some string"));
441 ///
442 /// // The boolean `false` is not a string.
443 /// assert_eq!(v["b"].as_str(), None);
444 ///
445 /// // JSON values are printed in JSON representation, so strings are in quotes.
446 /// //
447 /// // The value is: "some string"
448 /// println!("The value is: {}", v["a"]);
449 ///
450 /// // Rust strings are printed without quotes.
451 /// //
452 /// // The value is: some string
453 /// println!("The value is: {}", v["a"].as_str().unwrap());
454 /// ```
455 pub fn as_str(&self) -> Option<&str> {
456 match self {
457 Value::String(s) => Some(s),
458 _ => None,
459 }
460 }
461
462 /// Returns true if the `Value` is a Number. Returns false otherwise.
463 ///
464 /// ```
465 /// # use serde_json::json;
466 /// #
467 /// let v = json!({ "a": 1, "b": "2" });
468 ///
469 /// assert!(v["a"].is_number());
470 ///
471 /// // The string `"2"` is a string, not a number.
472 /// assert!(!v["b"].is_number());
473 /// ```
474 pub fn is_number(&self) -> bool {
475 match *self {
476 Value::Number(_) => true,
477 _ => false,
478 }
479 }
480
481 /// Returns true if the `Value` is an integer between `i64::MIN` and
482 /// `i64::MAX`.
483 ///
484 /// For any Value on which `is_i64` returns true, `as_i64` is guaranteed to
485 /// return the integer value.
486 ///
487 /// ```
488 /// # use serde_json::json;
489 /// #
490 /// let big = i64::max_value() as u64 + 10;
491 /// let v = json!({ "a": 64, "b": big, "c": 256.0 });
492 ///
493 /// assert!(v["a"].is_i64());
494 ///
495 /// // Greater than i64::MAX.
496 /// assert!(!v["b"].is_i64());
497 ///
498 /// // Numbers with a decimal point are not considered integers.
499 /// assert!(!v["c"].is_i64());
500 /// ```
501 pub fn is_i64(&self) -> bool {
502 match self {
503 Value::Number(n) => n.is_i64(),
504 _ => false,
505 }
506 }
507
508 /// Returns true if the `Value` is an integer between zero and `u64::MAX`.
509 ///
510 /// For any Value on which `is_u64` returns true, `as_u64` is guaranteed to
511 /// return the integer value.
512 ///
513 /// ```
514 /// # use serde_json::json;
515 /// #
516 /// let v = json!({ "a": 64, "b": -64, "c": 256.0 });
517 ///
518 /// assert!(v["a"].is_u64());
519 ///
520 /// // Negative integer.
521 /// assert!(!v["b"].is_u64());
522 ///
523 /// // Numbers with a decimal point are not considered integers.
524 /// assert!(!v["c"].is_u64());
525 /// ```
526 pub fn is_u64(&self) -> bool {
527 match self {
528 Value::Number(n) => n.is_u64(),
529 _ => false,
530 }
531 }
532
533 /// Returns true if the `Value` is a number that can be represented by f64.
534 ///
535 /// For any Value on which `is_f64` returns true, `as_f64` is guaranteed to
536 /// return the floating point value.
537 ///
538 /// Currently this function returns true if and only if both `is_i64` and
539 /// `is_u64` return false but this is not a guarantee in the future.
540 ///
541 /// ```
542 /// # use serde_json::json;
543 /// #
544 /// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
545 ///
546 /// assert!(v["a"].is_f64());
547 ///
548 /// // Integers.
549 /// assert!(!v["b"].is_f64());
550 /// assert!(!v["c"].is_f64());
551 /// ```
552 pub fn is_f64(&self) -> bool {
553 match self {
554 Value::Number(n) => n.is_f64(),
555 _ => false,
556 }
557 }
558
559 /// If the `Value` is an integer, represent it as i64 if possible. Returns
560 /// None otherwise.
561 ///
562 /// ```
563 /// # use serde_json::json;
564 /// #
565 /// let big = i64::max_value() as u64 + 10;
566 /// let v = json!({ "a": 64, "b": big, "c": 256.0 });
567 ///
568 /// assert_eq!(v["a"].as_i64(), Some(64));
569 /// assert_eq!(v["b"].as_i64(), None);
570 /// assert_eq!(v["c"].as_i64(), None);
571 /// ```
572 pub fn as_i64(&self) -> Option<i64> {
573 match self {
574 Value::Number(n) => n.as_i64(),
575 _ => None,
576 }
577 }
578
579 /// If the `Value` is an integer, represent it as u64 if possible. Returns
580 /// None otherwise.
581 ///
582 /// ```
583 /// # use serde_json::json;
584 /// #
585 /// let v = json!({ "a": 64, "b": -64, "c": 256.0 });
586 ///
587 /// assert_eq!(v["a"].as_u64(), Some(64));
588 /// assert_eq!(v["b"].as_u64(), None);
589 /// assert_eq!(v["c"].as_u64(), None);
590 /// ```
591 pub fn as_u64(&self) -> Option<u64> {
592 match self {
593 Value::Number(n) => n.as_u64(),
594 _ => None,
595 }
596 }
597
598 /// If the `Value` is a number, represent it as f64 if possible. Returns
599 /// None otherwise.
600 ///
601 /// ```
602 /// # use serde_json::json;
603 /// #
604 /// let v = json!({ "a": 256.0, "b": 64, "c": -64 });
605 ///
606 /// assert_eq!(v["a"].as_f64(), Some(256.0));
607 /// assert_eq!(v["b"].as_f64(), Some(64.0));
608 /// assert_eq!(v["c"].as_f64(), Some(-64.0));
609 /// ```
610 pub fn as_f64(&self) -> Option<f64> {
611 match self {
612 Value::Number(n) => n.as_f64(),
613 _ => None,
614 }
615 }
616
617 /// Returns true if the `Value` is a Boolean. Returns false otherwise.
618 ///
619 /// For any Value on which `is_boolean` returns true, `as_bool` is
620 /// guaranteed to return the boolean value.
621 ///
622 /// ```
623 /// # use serde_json::json;
624 /// #
625 /// let v = json!({ "a": false, "b": "false" });
626 ///
627 /// assert!(v["a"].is_boolean());
628 ///
629 /// // The string `"false"` is a string, not a boolean.
630 /// assert!(!v["b"].is_boolean());
631 /// ```
632 pub fn is_boolean(&self) -> bool {
633 self.as_bool().is_some()
634 }
635
636 /// If the `Value` is a Boolean, returns the associated bool. Returns None
637 /// otherwise.
638 ///
639 /// ```
640 /// # use serde_json::json;
641 /// #
642 /// let v = json!({ "a": false, "b": "false" });
643 ///
644 /// assert_eq!(v["a"].as_bool(), Some(false));
645 ///
646 /// // The string `"false"` is a string, not a boolean.
647 /// assert_eq!(v["b"].as_bool(), None);
648 /// ```
649 pub fn as_bool(&self) -> Option<bool> {
650 match *self {
651 Value::Bool(b) => Some(b),
652 _ => None,
653 }
654 }
655
656 /// Returns true if the `Value` is a Null. Returns false otherwise.
657 ///
658 /// For any Value on which `is_null` returns true, `as_null` is guaranteed
659 /// to return `Some(())`.
660 ///
661 /// ```
662 /// # use serde_json::json;
663 /// #
664 /// let v = json!({ "a": null, "b": false });
665 ///
666 /// assert!(v["a"].is_null());
667 ///
668 /// // The boolean `false` is not null.
669 /// assert!(!v["b"].is_null());
670 /// ```
671 pub fn is_null(&self) -> bool {
672 self.as_null().is_some()
673 }
674
675 /// If the `Value` is a Null, returns (). Returns None otherwise.
676 ///
677 /// ```
678 /// # use serde_json::json;
679 /// #
680 /// let v = json!({ "a": null, "b": false });
681 ///
682 /// assert_eq!(v["a"].as_null(), Some(()));
683 ///
684 /// // The boolean `false` is not null.
685 /// assert_eq!(v["b"].as_null(), None);
686 /// ```
687 pub fn as_null(&self) -> Option<()> {
688 match *self {
689 Value::Null => Some(()),
690 _ => None,
691 }
692 }
693
694 /// Looks up a value by a JSON Pointer.
695 ///
696 /// JSON Pointer defines a string syntax for identifying a specific value
697 /// within a JavaScript Object Notation (JSON) document.
698 ///
699 /// A Pointer is a Unicode string with the reference tokens separated by `/`.
700 /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The
701 /// addressed value is returned and if there is no such value `None` is
702 /// returned.
703 ///
704 /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
705 ///
706 /// # Examples
707 ///
708 /// ```
709 /// # use serde_json::json;
710 /// #
711 /// let data = json!({
712 /// "x": {
713 /// "y": ["z", "zz"]
714 /// }
715 /// });
716 ///
717 /// assert_eq!(data.pointer("/x/y/1").unwrap(), &json!("zz"));
718 /// assert_eq!(data.pointer("/a/b/c"), None);
719 /// ```
720 pub fn pointer(&self, pointer: &str) -> Option<&Value> {
721 if pointer.is_empty() {
722 return Some(self);
723 }
724 if !pointer.starts_with('/') {
725 return None;
726 }
727 pointer
728 .split('/')
729 .skip(1)
730 .map(|x| x.replace("~1", "/").replace("~0", "~"))
731 .map(Arc::new)
732 .try_fold(self, |target, token| match target {
733 Value::Object(map) => map.get(&**token),
734 Value::Array(list) => parse_index(&token).and_then(|x| list.get(x)),
735 _ => None,
736 })
737 }
738
739 /// Looks up a value by a JSON Pointer and returns a mutable reference to
740 /// that value.
741 ///
742 /// JSON Pointer defines a string syntax for identifying a specific value
743 /// within a JavaScript Object Notation (JSON) document.
744 ///
745 /// A Pointer is a Unicode string with the reference tokens separated by `/`.
746 /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The
747 /// addressed value is returned and if there is no such value `None` is
748 /// returned.
749 ///
750 /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
751 ///
752 /// # Example of Use
753 ///
754 /// ```
755 /// use serde_json::Value;
756 ///
757 /// fn main() {
758 /// let s = r#"{"x": 1.0, "y": 2.0}"#;
759 /// let mut value: Value = serde_json::from_str(s).unwrap();
760 ///
761 /// // Check value using read-only pointer
762 /// assert_eq!(value.pointer("/x"), Some(&1.0.into()));
763 /// // Change value with direct assignment
764 /// *value.pointer_mut("/x").unwrap() = 1.5.into();
765 /// // Check that new value was written
766 /// assert_eq!(value.pointer("/x"), Some(&1.5.into()));
767 /// // Or change the value only if it exists
768 /// value.pointer_mut("/x").map(|v| *v = 1.5.into());
769 ///
770 /// // "Steal" ownership of a value. Can replace with any valid Value.
771 /// let old_x = value.pointer_mut("/x").map(Value::take).unwrap();
772 /// assert_eq!(old_x, 1.5);
773 /// assert_eq!(value.pointer("/x").unwrap(), &Value::Null);
774 /// }
775 /// ```
776 pub fn pointer_mut(&mut self, pointer: &str) -> Option<&mut Value> {
777 if pointer.is_empty() {
778 return Some(self);
779 }
780 if !pointer.starts_with('/') {
781 return None;
782 }
783 pointer
784 .split('/')
785 .skip(1)
786 .map(|x| x.replace("~1", "/").replace("~0", "~"))
787 .map(Arc::new)
788 .try_fold(self, |target, token| match target {
789 Value::Object(map) => map.get_mut(&**token),
790 Value::Array(list) => parse_index(&token).and_then(move |x| list.get_mut(x)),
791 _ => None,
792 })
793 }
794
795 /// Takes the value out of the `Value`, leaving a `Null` in its place.
796 ///
797 /// ```
798 /// # use serde_json::json;
799 /// #
800 /// let mut v = json!({ "x": "y" });
801 /// assert_eq!(v["x"].take(), json!("y"));
802 /// assert_eq!(v, json!({ "x": null }));
803 /// ```
804 pub fn take(&mut self) -> Value {
805 ::std::mem::replace(self, Value::Null)
806 }
807}
808
809/// The default value is `Value::Null`.
810///
811/// This is useful for handling omitted `Value` fields when deserializing.
812///
813/// # Examples
814///
815/// ```
816/// # use serde::Deserialize;
817/// use serde_json::Value;
818///
819/// #[derive(Deserialize)]
820/// struct Settings {
821/// level: i32,
822/// #[serde(default)]
823/// extras: Value,
824/// }
825///
826/// # fn try_main() -> Result<(), serde_json::Error> {
827/// let data = r#" { "level": 42 } "#;
828/// let s: Settings = serde_json::from_str(data)?;
829///
830/// assert_eq!(s.level, 42);
831/// assert_eq!(s.extras, Value::Null);
832/// #
833/// # Ok(())
834/// # }
835/// #
836/// # try_main().unwrap()
837/// ```
838impl Default for Value {
839 fn default() -> Value {
840 Value::Null
841 }
842}
843
844impl PartialEq for Value {
845 fn eq(&self, other: &Self) -> bool {
846 match (self, other) {
847 (Value::Array(a), Value::Array(b)) => a.ptr_eq(b) || a == b,
848 (Value::Bool(a), Value::Bool(b)) => a == b,
849 (Value::Null, Value::Null) => true,
850 (Value::Number(a), Value::Number(b)) => a == b,
851
852 (Value::Object(a), Value::Object(b)) => a.ptr_eq(b) || a == b,
853 (Value::String(a), Value::String(b)) => Arc::ptr_eq(a, b) || a == b,
854 _ => false,
855 }
856 }
857}
858impl Eq for Value {}
859
860impl PartialEq<f64> for Value {
861 fn eq(&self, other: &f64) -> bool {
862 match self {
863 Value::Number(n) => n.as_f64() == Some(*other),
864 _ => false,
865 }
866 }
867}
868impl PartialEq<i64> for Value {
869 fn eq(&self, other: &i64) -> bool {
870 match self {
871 Value::Number(n) => n.as_i64() == Some(*other),
872 _ => false,
873 }
874 }
875}
876impl PartialEq<u64> for Value {
877 fn eq(&self, other: &u64) -> bool {
878 match self {
879 Value::Number(n) => n.as_u64() == Some(*other),
880 _ => false,
881 }
882 }
883}
884impl PartialEq<str> for Value {
885 fn eq(&self, other: &str) -> bool {
886 match self {
887 Value::String(s) => &**s == other,
888 _ => false,
889 }
890 }
891}
892
893// impl From<serde_json::Value> for Value {
894// fn from(value: serde_json::Value) -> Self {
895// match value {
896// serde_json::Value::Null => Value::Null,
897// serde_json::Value::Bool(a) => Value::Bool(a),
898// serde_json::Value::Number(a) => Value::Number(a),
899// serde_json::Value::String(a) => Value::String(Arc::new(a)),
900// serde_json::Value::Array(a) => Value::Array(a.into_iter().map(Value::from).collect()),
901// serde_json::Value::Object(a) => Value::Object(
902// a.into_iter()
903// .map(|(k, v)| (Arc::new(k), Value::from(v)))
904// .collect(),
905// ),
906// }
907// }
908// }
909// impl From<Value> for serde_json::Value {
910// fn from(value: Value) -> Self {
911// use serde_json::Value as JValue;
912// match value {
913// Value::Null => JValue::Null,
914// Value::Bool(x) => JValue::Bool(x),
915// Value::Number(x) => JValue::Number(x),
916// Value::String(x) => JValue::String(match Arc::try_unwrap(x) {
917// Ok(x) => x,
918// Err(x) => x.deref().to_owned(),
919// }),
920// Value::Array(x) => JValue::Array(x.into_iter().map(JValue::from).collect()),
921// Value::Object(x) => JValue::Object(
922// x.into_iter()
923// .map(|(k, v)| {
924// (
925// match Arc::try_unwrap(k) {
926// Ok(x) => x,
927// Err(x) => x.deref().to_owned(),
928// },
929// JValue::from(v),
930// )
931// })
932// .collect(),
933// ),
934// }
935// }
936// }
937
938pub fn to_value<T>(value: &T) -> Result<Value, Error>
939where
940 T: Serialize,
941{
942 value.serialize(ser::Serializer).map_err(|e| Error {
943 kind: ErrorKind::Serialization,
944 source: e,
945 })
946}
947
948pub fn from_value<T>(value: Value) -> Result<T, Error>
949where
950 T: DeserializeOwned,
951{
952 T::deserialize(value).map_err(|e| Error {
953 kind: ErrorKind::Deserialization,
954 source: e,
955 })
956}
957
958#[test]
959fn test_serialize_loop() {
960 let value = json!({
961 "a": "hello I'm a",
962 "b": 1,
963 "c": true,
964 "d": null,
965 "e": [123, "testing"],
966 "f": { "h": 'i'}
967 });
968 assert_eq!(
969 &serde_json::to_string(&value)
970 .unwrap(),
971 "{\"a\":\"hello I'm a\",\"b\":1,\"c\":true,\"d\":null,\"e\":[123,\"testing\"],\"f\":{\"h\":\"i\"}}"
972 );
973 assert_eq!(
974 value,
975 serde_json::from_str::<Value>(&serde_json::to_string(&value).unwrap()).unwrap(),
976 );
977
978 assert_eq!(value["f"]["h"].as_str().unwrap(), "i");
979}