### get() example Source: https://docs.rs/serde_json/latest/serde_json/map/struct.OccupiedEntry.html?search=std%3A%3Avec Example for the get() method, which returns a reference to the value in the entry. ```rust use serde_json::map::Entry; let mut map = serde_json::Map::new(); map.insert("serde".to_owned(), json!(12)); match map.entry("serde") { Entry::Occupied(occupied) => { assert_eq!(occupied.get(), 12); } Entry::Vacant(_) => unimplemented!(), } ``` -------------------------------- ### Entry key method example Source: https://docs.rs/serde_json/latest/serde_json/map/enum.Entry.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to use the key method to get a reference to the entry's key. ```rust let mut map = serde_json::Map::new(); assert_eq!(map.entry("serde").key(), &"serde"); ``` -------------------------------- ### as_mut example Source: https://docs.rs/serde_json/latest/serde_json/error/type.Result.html?search= Shows how to use as_mut to get mutable references to the Ok or Err values and modify them. ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### VacantEntry::key() example Source: https://docs.rs/serde_json/latest/serde_json/map/struct.VacantEntry.html?search=u32+-%3E+bool Shows how to use the key() method on a VacantEntry to get a reference to the key that would be used when inserting a value. The example matches on the Entry enum and asserts the key is "serde". ```rust use serde_json::map::Entry; let mut map = serde_json::Map::new(); match map.entry("serde") { Entry::Vacant(vacant) => { assert_eq!(vacant.key(), &"serde"); } Entry::Occupied(_) => unimplemented!(), } ``` -------------------------------- ### key() example Source: https://docs.rs/serde_json/latest/serde_json/map/struct.OccupiedEntry.html?search=std%3A%3Avec Example for the key() method, which returns a reference to the key in the entry. ```rust use serde_json::map::Entry; let mut map = serde_json::Map::new(); map.insert("serde".to_owned(), json!(12)); match map.entry("serde") { Entry::Occupied(occupied) => { assert_eq!(occupied.key(), &"serde"); } Entry::Vacant(_) => unimplemented!(), } ``` -------------------------------- ### insert() example Source: https://docs.rs/serde_json/latest/serde_json/map/struct.OccupiedEntry.html?search=std%3A%3Avec Example for the insert() method, which sets the value of the entry and returns the old value. ```rust use serde_json::map::Entry; let mut map = serde_json::Map::new(); map.insert("serde".to_owned(), json!(12)); match map.entry("serde") { Entry::Occupied(mut occupied) => { assert_eq!(occupied.insert(json!(13)), 12); assert_eq!(occupied.get(), 13); } Entry::Vacant(_) => unimplemented!(), } ``` -------------------------------- ### into_mut() example Source: https://docs.rs/serde_json/latest/serde_json/map/struct.OccupiedEntry.html?search=std%3A%3Avec Example for the into_mut() method, which converts the entry into a mutable reference to its value. ```rust use serde_json::map::Entry; let mut map = serde_json::Map::new(); map.insert("serde".to_owned(), json!([1, 2, 3])); match map.entry("serde") { Entry::Occupied(mut occupied) => { occupied.into_mut().as_array_mut().unwrap().push(json!(4)); } Entry::Vacant(_) => unimplemented!(), } assert_eq!(map["serde"].as_array().unwrap().len(), 4); ``` -------------------------------- ### take example Source: https://docs.rs/serde_json/latest/serde_json/enum.Value.html Takes the value out of the Value, leaving a Null in its place. The example shows that the original key becomes null. ```rust let mut v = json!({ "x": "y" }); assert_eq!(v["x"].take(), json!("y")); assert_eq!(v, json!({ "x": null })); ``` -------------------------------- ### iter example Source: https://docs.rs/serde_json/latest/serde_json/error/type.Result.html?search= Demonstrates `iter` to get an iterator over the possibly contained value. Yields one value for `Ok` and none for `Err`. ```rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### map example Source: https://docs.rs/serde_json/latest/serde_json/error/type.Result.html?search= Shows how to apply a function to the Ok value of a Result, leaving Err untouched. The example parses lines and multiplies by two. ```rust let line = "1\n2\n3\n4\n"; for num in line.lines() { match num.parse::().map(|i| i * 2) { Ok(n) => println!("{n}"), Err(..) => {} } } ``` -------------------------------- ### is_err_and example Source: https://docs.rs/serde_json/latest/serde_json/error/type.Result.html?search= Shows how to use is_err_and to check if a Result is Err and the error matches a predicate. Includes examples with different error types and ownership. ```rust use std::io::{Error, ErrorKind}; let x: Result = Err(Error::new(ErrorKind::NotFound, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true); let x: Result = Err(Error::new(ErrorKind::PermissionDenied, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result = Ok(123); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result = Err("ownership".to_string()); assert_eq!(x.as_ref().is_err_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### get_mut() example Source: https://docs.rs/serde_json/latest/serde_json/map/struct.OccupiedEntry.html?search=std%3A%3Avec Example for the get_mut() method, which returns a mutable reference to the value in the entry. ```rust use serde_json::map::Entry; let mut map = serde_json::Map::new(); map.insert("serde".to_owned(), json!([1, 2, 3])); match map.entry("serde") { Entry::Occupied(mut occupied) => { occupied.get_mut().as_array_mut().unwrap().push(json!(4)); } Entry::Vacant(_) => unimplemented!(), } assert_eq!(map["serde"].as_array().unwrap().len(), 4); ``` -------------------------------- ### pointer example Source: https://docs.rs/serde_json/latest/serde_json/enum.Value.html Looks up a value by a JSON Pointer string. The example shows accessing a nested array element and a missing path. ```rust let data = json!({ "x": { "y": ["z", "zz"] } }); assert_eq!(data.pointer("/x/y/1").unwrap(), &json!("zz")); assert_eq!(data.pointer("/a/b/c"), None); ``` -------------------------------- ### Get value from OccupiedEntry Source: https://docs.rs/serde_json/latest/serde_json/map/struct.OccupiedEntry.html?search= Use `OccupiedEntry::get` to get a reference to the value in the entry. The example asserts that the value is 12. ```rust use serde_json::map::Entry; let mut map = serde_json::Map::new(); map.insert("serde".to_owned(), json!(12)); match map.entry("serde") { Entry::Occupied(occupied) => { assert_eq!(occupied.get(), 12); } Entry::Vacant(_) => unimplemented!(), } ``` -------------------------------- ### expect recommended message style example Source: https://docs.rs/serde_json/latest/serde_json/error/type.Result.html?search= Shows the recommended message style for `expect`: describe why the result should be `Ok`. The example expects an environment variable to be set and panics with a descriptive message if not. ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### RawValue::get example Source: https://docs.rs/serde_json/latest/serde_json/value/struct.RawValue.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Access the JSON text underlying a RawValue with get(). The example deserializes a struct with a borrowed RawValue field and inspects the payload string to decide how to handle it. ```rust use serde::Deserialize; use serde_json::{Result, value::RawValue}; #[derive(Deserialize)] struct Response<'a> { code: u32, #[serde(borrow)] payload: &'a RawValue, } fn process(input: &str) -> Result<()> { let response: Response = serde_json::from_str(input)?; let payload = response.payload.get(); if payload.starts_with('{') { // handle a payload which is a JSON map } else { // handle any other type } Ok(()) } fn main() -> Result<()> { process(r#" {"code": 200, "payload": {}} "#)?; Ok(()) } ``` -------------------------------- ### iter_mut example Source: https://docs.rs/serde_json/latest/serde_json/error/type.Result.html?search= Shows `iter_mut` to get a mutable iterator over the possibly contained value. The example modifies the `Ok` value to 40 and asserts the result; for `Err` it yields `None`. ```rust let mut x: Result = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### ok example Source: https://docs.rs/serde_json/latest/serde_json/error/type.Result.html?search= Shows how to convert a Result to an Option, returning Some(value) for Ok and None for Err. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` -------------------------------- ### as_deref_mut example Source: https://docs.rs/serde_json/latest/serde_json/error/type.Result.html?search= Shows `as_deref_mut` to get a mutable reference to the `Ok` value, allowing in-place modification. The example uppercases the string and asserts equality for both `Ok` and `Err` cases. ```rust let mut s = "HELLO".to_string(); let mut x: Result = Ok("hello".to_string()); let y: Result<&mut str, &mut u32> = Ok(&mut s); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); let mut i = 42; let mut x: Result = Err(42); let y: Result<&mut str, &mut u32> = Err(&mut i); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); ``` -------------------------------- ### Mutably get object as Map with as_object_mut Source: https://docs.rs/serde_json/latest/serde_json/enum.Value.html Uses as_object_mut to get a mutable reference to the Map if the Value is an Object, otherwise returns None. The example clears the nested object. ```rust let mut v = json!({ "a": { "nested": true } }); v["a"].as_object_mut().unwrap().clear(); assert_eq!(v, json!({ "a": {} })); ``` -------------------------------- ### Get key from OccupiedEntry Source: https://docs.rs/serde_json/latest/serde_json/map/struct.OccupiedEntry.html?search= Use `OccupiedEntry::key` to get a reference to the key of an occupied entry. The example creates a map with a single entry and matches on the entry to assert the key is "serde". ```rust use serde_json::map::Entry; let mut map = serde_json::Map::new(); map.insert("serde".to_owned(), json!(12)); match map.entry("serde") { Entry::Occupied(occupied) => { assert_eq!(occupied.key(), &"serde"); } Entry::Vacant(_) => unimplemented!(), } ``` -------------------------------- ### as_ref example Source: https://docs.rs/serde_json/latest/serde_json/error/type.Result.html?search= Shows how to convert a &Result to a Result of references, leaving the original in place. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### Display implementation for Value with compact and pretty formatting Source: https://docs.rs/serde_json/latest/src/serde_json/value/mod.rs.html Display implementation for Value that shows compact and pretty formatting examples using the json! macro and format!. ```rust impl Display for Value { /// Display a JSON value as a string. /// /// ``` /// # use serde_json::json; /// # /// let json = json!({ "city": "London", "street": "10 Downing Street" }); /// /// // Compact format: /// // /// // {"city":"London","street":"10 Downing Street"} /// let compact = format!("{}", json); /// assert_eq!(compact, /// "{\"city\":\"London\",\"street\":\"10 Downing Street\"}"); /// /// // Pretty format: /// // /// // { /// // "city": "London", ``` -------------------------------- ### Get key from VacantEntry with serde_json::map::Entry Source: https://docs.rs/serde_json/latest/serde_json/map/struct.VacantEntry.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to use the `key` method on a `VacantEntry` to get a reference to the key that would be used when inserting a value. The example matches on the result of `map.entry("serde")` and asserts that the key is `"serde"`. ```rust use serde_json::map::Entry; let mut map = serde_json::Map::new(); match map.entry("serde") { Entry::Vacant(vacant) => { assert_eq!(vacant.key(), &"serde"); } Entry::Occupied(_) => unimplemented!(), } ``` -------------------------------- ### Indexing into a JSON Value with string and usize Source: https://docs.rs/serde_json/latest/serde_json/value/trait.Index.html Shows how to use the Index trait to access nested values in a serde_json::Value. The example creates a JSON object with an array, then indexes with a string to get the array and with an integer to get the first element. The assertion confirms the value is 1. ```rust let data = json!({ "inner": [1, 2, 3] }); // Data is a JSON map so it can be indexed with a string. let inner = &data["inner"]; // Inner is a JSON array so it can be indexed with an integer. let first = &inner[0]; assert_eq!(first, 1); ``` -------------------------------- ### as_array: Get vector from JSON array Source: https://docs.rs/serde_json/latest/serde_json/enum.Value.html Returns the associated vector if the Value is an Array, otherwise None. The example shows that indexing into a JSON object with a string key returns a Value, and as_array() unwraps it to get the vector's length. For a non-array value, it returns None. ```rust let v = json!({ "a": ["an", "array"], "b": { "an": "object" } }); // The length of `["an", "array"]` is 2 elements. assert_eq!(v["a"].as_array().unwrap().len(), 2); // The object `{"an": "object"}` is not an array. assert_eq!(v["b"].as_array(), None); ``` -------------------------------- ### as_array_mut: Get mutable vector from JSON array Source: https://docs.rs/serde_json/latest/serde_json/enum.Value.html Returns a mutable reference to the vector if the Value is an Array, otherwise None. The example clears the array in place and verifies the mutation. ```rust let mut v = json!({ "a": ["an", "array"] }); v["a"].as_array_mut().unwrap().clear(); assert_eq!(v, json!({ "a": [] })); ``` -------------------------------- ### begin_object Source: https://docs.rs/serde_json/latest/serde_json/ser/trait.Formatter.html?search=u32+-%3E+bool Begins writing a JSON object. ```APIDOC ## begin_object ### Description Begins writing a JSON object. ### Method begin_object ### Parameters - **writer** (`&mut W`) - The output writer. ### Returns - `Result<()>` - Ok if successful, Err otherwise. ### Example ```rust // Implementation provided by the trait ``` ``` -------------------------------- ### as_number: Get Number from JSON value Source: https://docs.rs/serde_json/latest/serde_json/enum.Value.html Returns the associated Number if the Value is a Number, otherwise None. The example shows conversions for integer, float, and negative values, and that a string is not a number. ```rust let v = json!({ "a": 1, "b": 2.2, "c": -3, "d": "4" }); assert_eq!(v["a"].as_number(), Some(&Number::from(1u64))); assert_eq!(v["b"].as_number(), Some(&Number::from_f64(2.2).unwrap())); assert_eq!(v["c"].as_number(), Some(&Number::from(-3i64))); // The string `"4"` is not a number. assert_eq!(v["d"].as_number(), None); ``` -------------------------------- ### begin_object Source: https://docs.rs/serde_json/latest/serde_json/ser/struct.CompactFormatter.html?search= Method to call before every object, writing an opening brace. ```APIDOC ## begin_object ### Description Called before every object. Writes a `{` to the specified writer. ### Method begin_object ### Signature `fn begin_object(&mut self, writer: &mut W) -> Result<()> where W: ?Sized + Write` ### Parameters - **writer** (`&mut W`) - Required - The writer to write to. ### Return Value `Result<()>` - Indicates success or failure. ``` -------------------------------- ### Entry or_insert example Source: https://docs.rs/serde_json/latest/serde_json/map/enum.Entry.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates or_insert inserting a default value if the entry is vacant. ```rust let mut map = serde_json::Map::new(); map.entry("serde").or_insert(json!(12)); assert_eq!(map["serde"], 12); ``` -------------------------------- ### Mutate value via OccupiedEntry::get_mut Source: https://docs.rs/serde_json/latest/serde_json/map/struct.OccupiedEntry.html?search= Use `OccupiedEntry::get_mut` to get a mutable reference to the value and modify it in place. The example pushes a new element to the array and verifies the length becomes 4. ```rust use serde_json::map::Entry; let mut map = serde_json::Map::new(); map.insert("serde".to_owned(), json!([1, 2, 3])); match map.entry("serde") { Entry::Occupied(mut occupied) => { occupied.get_mut().as_array_mut().unwrap().push(json!(4)); } Entry::Vacant(_) => unimplemented!(), } assert_eq!(map["serde"].as_array().unwrap().len(), 4); ``` -------------------------------- ### Display a JSON value as a string with format! Source: https://docs.rs/serde_json/latest/serde_json/enum.Value.html Shows how to use the Display implementation for Value with format! to produce compact and pretty JSON strings. The compact format uses {} and the pretty format uses {:#}. The example asserts the exact output strings. ```rust let json = json!({ "city": "London", "street": "10 Downing Street" }); // Compact format: // // {"city":"London","street":"10 Downing Street"} let compact = format!("{}", json); assert_eq!(compact, "{\"city\":\"London\",\"street\":\"10 Downing Street\"}"); // Pretty format: // // { // "city": "London", // "street": "10 Downing Street" // } let pretty = format!("{:#}", json); assert_eq!(pretty, "{\n \"city\": \"London\",\n \"street\": \"10 Downing Street\"}"); ``` -------------------------------- ### as_str: Get string slice from JSON string Source: https://docs.rs/serde_json/latest/serde_json/enum.Value.html Returns the associated str if the Value is a String, otherwise None. The example also shows that JSON values print with quotes, while Rust strings print without quotes. ```rust let v = json!({ "a": "some string", "b": false }); assert_eq!(v["a"].as_str(), Some("some string")); // The boolean `false` is not a string. assert_eq!(v["b"].as_str(), None); // JSON values are printed in JSON representation, so strings are in quotes. // // The value is: "some string" println!("The value is: {}", v["a"]); // Rust strings are printed without quotes. // // The value is: some string println!("The value is: {}", v["a"].as_str().unwrap()); ``` -------------------------------- ### Begin raw value buffering Source: https://docs.rs/serde_json/latest/src/serde_json/read.rs.html?search= Starts buffering raw value bytes by initializing `self.raw_buffer` to an empty vector. Only available with the `raw_value` feature. ```rust #[cfg(feature = "raw_value")] fn begin_raw_buffering(&mut self) { self.raw_buffer = Some(Vec::new()); } ``` -------------------------------- ### Index trait definition and implementations Source: https://docs.rs/serde_json/latest/src/serde_json/value/index.rs.html The Index trait is sealed and implemented for str and String. It provides methods to index into Value, get mutable references, and insert null for missing keys. The example shows indexing a JSON object with a string and an array with an integer. ```rust use super::Value; use crate::map::Map; use alloc::borrow::ToOwned; use alloc::string::String; use core::fmt::{self, Display}; use core::ops; /// A type that can be used to index into a `serde_json::Value`. /// /// The [`get`] and [`get_mut`] methods of `Value` accept any type that /// implements `Index`, as does the [square-bracket indexing operator]. This /// trait is implemented for strings which are used as the index into a JSON /// map, and for `usize` which is used as the index into a JSON array. /// /// [`get`]: Value::get /// [`get_mut`]: Value::get_mut /// [square-bracket indexing operator]: Value#impl-Index%3CI%3E-for-Value /// /// This trait is sealed and cannot be implemented for types outside of /// `serde_json`. /// /// # Examples /// /// ``` /// # use serde_json::json; /// # /// let data = json!({ "inner": [1, 2, 3] }); /// /// // Data is a JSON map so it can be indexed with a string. /// let inner = &data["inner"]; /// /// // Inner is a JSON array so it can be indexed with an integer. /// let first = &inner[0]; /// /// assert_eq!(first, 1); /// ``` pub trait Index: private::Sealed { /// Return None if the key is not already in the array or object. #[doc(hidden)] fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value>; /// Return None if the key is not already in the array or object. #[doc(hidden)] fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value>; /// Panic if array index out of bounds. If key is not already in the object, /// insert it with a value of null. Panic if Value is a type that cannot be /// indexed into, except if Value is null then it can be treated as an empty /// object. #[doc(hidden)] fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value; } impl Index for usize { fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { match v { Value::Array(vec) => vec.get(*self), _ => None, } } fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { match v { Value::Array(vec) => vec.get_mut(*self), _ => None, } } fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { match v { Value::Array(vec) => { let len = vec.len(); vec.get_mut(*self).unwrap_or_else(|| { { ::core::panicking::panic_fmt(format_args!("cannot access index {0} of JSON array of length {1}", self, len)); }panic!( "cannot access index {} of JSON array of length {}", self, len ) }) } _ => { ::core::panicking::panic_fmt(format_args!("cannot access index {0} of JSON {1}", self, Type(v))); }panic!("cannot access index {} of JSON {}", self, Type(v)), } } } impl Index for str { fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { match v { Value::Object(map) => map.get(self), _ => None, } } fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { match v { Value::Object(map) => map.get_mut(self), _ => None, } } fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { if let Value::Null = v { *v = Value::Object(Map::new()); } match v { Value::Object(map) => map.entry(self.to_owned()).or_insert(Value::Null), _ => { ::core::panicking::panic_fmt(format_args!("cannot access key {0:?} in JSON {1}", self, Type(v))); }panic!("cannot access key {:?} in JSON {}", self, Type(v)), } } } impl Index for &T where T: ?Sized + Index, { fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { (**self).index_into(v) } fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { (**self).index_into_mut(v) } fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { (**self).index_or_insert(v) } } ``` -------------------------------- ### begin_object_key Source: https://docs.rs/serde_json/latest/serde_json/ser/struct.CompactFormatter.html?search= Method to call before every object key. ```APIDOC ## begin_object_key ### Description Called before every object key. ### Method begin_object_key ### Signature `fn begin_object_key(&mut self, writer: &mut W, first: bool) -> Result<()> where W: ?Sized + Write` ### Parameters - **writer** (`&mut W`) - Required - The writer to write to. - **first** (`bool`) - Required - Indicates if this is the first key in the object. ### Return Value `Result<()>` - Indicates success or failure. ``` -------------------------------- ### serde_json::error module: Error struct and methods Source: https://docs.rs/serde_json/latest/src/serde_json/error.rs.html The beginning of the serde_json error module, defining the `Error` struct, the `Result` alias, and the `Error` methods for line, column, classify, is_io, is_syntax, is_data, and is_eof. The code is truncated at the start of an example for `io_error_kind`. ```rust //! When serializing or deserializing JSON goes wrong. use crate::io; use alloc::boxed::Box; use alloc::string::{String, ToString}; use core::fmt::{self, Debug, Display}; use core::result; use core::str::FromStr; use serde::{de, ser}; #[cfg(feature = "std")] use std::error; #[cfg(feature = "std")] use std::io::ErrorKind; /// This type represents all possible errors that can occur when serializing or /// deserializing JSON data. pub struct Error { /// This `Box` allows us to keep the size of `Error` as small as possible. A /// larger `Error` type was substantially slower due to all the functions /// that pass around `Result`. err: Box, } /// Alias for a `Result` with the error type `serde_json::Error`. pub type Result = result::Result; impl Error { /// One-based line number at which the error was detected. /// /// Characters in the first line of the input (before the first newline /// character) are in line 1. pub fn line(&self) -> usize { self.err.line } /// One-based column number at which the error was detected. /// /// The first character in the input and any characters immediately /// following a newline character are in column 1. /// /// Note that errors may occur in column 0, for example if a read from an /// I/O stream fails immediately following a previously read newline /// character. pub fn column(&self) -> usize { self.err.column } /// Categorizes the cause of this error. /// /// - `Category::Io` - failure to read or write bytes on an I/O stream /// - `Category::Syntax` - input that is not syntactically valid JSON /// - `Category::Data` - input data that is semantically incorrect /// - `Category::Eof` - unexpected end of the input data pub fn classify(&self) -> Category { match self.err.code { ErrorCode::Message(_) => Category::Data, ErrorCode::Io(_) => Category::Io, ErrorCode::EofWhileParsingList | ErrorCode::EofWhileParsingObject | ErrorCode::EofWhileParsingString | ErrorCode::EofWhileParsingValue => Category::Eof, ErrorCode::ExpectedColon | ErrorCode::ExpectedListCommaOrEnd | ErrorCode::ExpectedObjectCommaOrEnd | ErrorCode::ExpectedSomeIdent | ErrorCode::ExpectedSomeValue | ErrorCode::ExpectedDoubleQuote | ErrorCode::InvalidEscape | ErrorCode::InvalidNumber | ErrorCode::NumberOutOfRange | ErrorCode::InvalidUnicodeCodePoint | ErrorCode::ControlCharacterWhileParsingString | ErrorCode::KeyMustBeAString | ErrorCode::ExpectedNumericKey | ErrorCode::FloatKeyMustBeFinite | ErrorCode::LoneLeadingSurrogateInHexEscape | ErrorCode::TrailingComma | ErrorCode::TrailingCharacters | ErrorCode::UnexpectedEndOfHexEscape | ErrorCode::RecursionLimitExceeded => Category::Syntax, } } /// Returns true if this error was caused by a failure to read or write /// bytes on an I/O stream. pub fn is_io(&self) -> bool { self.classify() == Category::Io } /// Returns true if this error was caused by input that was not /// syntactically valid JSON. pub fn is_syntax(&self) -> bool { self.classify() == Category::Syntax } /// Returns true if this error was caused by input data that was /// semantically incorrect. /// /// For example, JSON containing a number is semantically incorrect when the /// type being deserialized into holds a String. pub fn is_data(&self) -> bool { self.classify() == Category::Data } /// Returns true if this error was caused by prematurely reaching the end of /// the input data. /// /// Callers that process streaming input may be interested in retrying the /// deserialization once more data is available. pub fn is_eof(&self) -> bool { self.classify() == Category::Eof } /// The kind reported by the underlying standard library I/O error, if this /// error was caused by a failure to read or write bytes on an I/O stream. /// /// # Example /// /// ``` /// use serde_json::Value; /// use std::io::{self, ErrorKind, Read}; /// use std::process; /// /// struct ReaderThatWillTimeOut<'a>(&'a [u8]); /// ``` -------------------------------- ### get Source: https://docs.rs/serde_json/latest/serde_json/map/struct.OccupiedEntry.html?search=std%3A%3Avec Gets a reference to the value in the entry. ```APIDOC ## get ### Description Gets a reference to the value in the entry. ### Method get ### Signature pub fn get(&self) -> &Value ### Parameters None ### Returns - **&Value** - A reference to the value. ### Example ```rust use serde_json::map::Entry; let mut map = serde_json::Map::new(); map.insert("serde".to_owned(), json!(12)); match map.entry("serde") { Entry::Occupied(occupied) => { assert_eq!(occupied.get(), 12); } Entry::Vacant(_) => unimplemented!(), } ``` ``` -------------------------------- ### and_then example function Source: https://docs.rs/serde_json/latest/serde_json/error/type.Result.html?search= Example function for and_then, showing control flow based on Result values. The function squares a number and converts it to a string, returning an error on overflow. ```rust fn sq_then_to_string(x: u32) -> Result { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } ``` -------------------------------- ### err example Source: https://docs.rs/serde_json/latest/serde_json/error/type.Result.html?search= Shows how to convert a Result to an Option, returning Some(error) for Err and None for Ok. ```rust let x: Result = Ok(2); assert_eq!(x.err(), None); let x: Result = Err("Nothing here"); assert_eq!(x.err(), Some("Nothing here")); ```