### Implementations of InnerAsRefMut Source: https://docs.rs/tinyjson/2.5.1/tinyjson/trait.InnerAsRefMut.html Examples of how the trait is implemented for various types including primitives, strings, and collections. ```rust fn json_value_as_mut(v: &mut JsonValue) -> Option<&mut bool> ``` ```rust fn json_value_as_mut(v: &mut JsonValue) -> Option<&mut f64> ``` ```rust fn json_value_as_mut(v: &mut JsonValue) -> Option<&mut String> ``` ```rust fn json_value_as_mut(v: &mut JsonValue) -> Option<&mut Vec> ``` ```rust fn json_value_as_mut( v: &mut JsonValue, ) -> Option<&mut HashMap> ``` -------------------------------- ### InnerAsRef Implementations Source: https://docs.rs/tinyjson/2.5.1/tinyjson/trait.InnerAsRef.html Examples of implementing InnerAsRef for various standard types to allow safe access to JsonValue contents. ```rust impl InnerAsRef for bool fn json_value_as(v: &JsonValue) -> Option<&bool> ``` ```rust impl InnerAsRef for f64 fn json_value_as(v: &JsonValue) -> Option<&f64> ``` ```rust impl InnerAsRef for () fn json_value_as(v: &JsonValue) -> Option<&()> ``` ```rust impl InnerAsRef for String fn json_value_as(v: &JsonValue) -> Option<&String> ``` ```rust impl InnerAsRef for Vec fn json_value_as(v: &JsonValue) -> Option<&Vec> ``` ```rust impl InnerAsRef for HashMap fn json_value_as(v: &JsonValue) -> Option<&HashMap> ``` -------------------------------- ### Retrieve inner value reference Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html Use get to access an immutable reference to the inner value, returning None if the type does not match. ```rust use tinyjson::JsonValue; let value: JsonValue = "[1, 2, 3]".parse().unwrap(); let vec: &Vec<_> = value.get().unwrap(); assert_eq!(vec[0], JsonValue::from(1.0)); // Try to convert with incorrect type assert!(value.get::().is_none()); ``` -------------------------------- ### Configuring indentation Source: https://docs.rs/tinyjson/2.5.1/tinyjson/struct.JsonGenerator.html Shows how to set an indentation string for formatted JSON output. ```rust use tinyjson::{JsonGenerator, JsonValue}; let v = JsonValue::from(vec![1.0.into(), 2.0.into(), 3.0.into()]); let mut buf = vec![]; let mut gen = JsonGenerator::new(&mut buf).indent(" "); gen.generate(&v).unwrap(); assert_eq!(String::from_utf8(buf).unwrap(), "[ 1, 2, 3 ]"); ``` -------------------------------- ### Comparing formatted and unformatted output Source: https://docs.rs/tinyjson/2.5.1/tinyjson/struct.JsonGenerator.html Illustrates the difference between default serialization and serialization with a specified indent. ```rust use tinyjson::{JsonGenerator, JsonValue}; let v = JsonValue::from(vec![1.0.into(), 2.0.into(), 3.0.into()]); let mut buf = vec![]; let mut gen = JsonGenerator::new(&mut buf); gen.generate(&v).unwrap(); assert_eq!(String::from_utf8(buf).unwrap(), "[1,2,3]"); let mut buf = vec![]; let mut gen = JsonGenerator::new(&mut buf).indent(" "); // with 2-spaces indent gen.generate(&v).unwrap(); assert_eq!(String::from_utf8(buf).unwrap(), "[ 1, 2, 3 ]"); ``` -------------------------------- ### Into Ok value Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Use into_ok to retrieve the Ok value without risk of panicking, typically used with infallible results. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } ``` -------------------------------- ### Basic JsonGenerator usage Source: https://docs.rs/tinyjson/2.5.1/tinyjson/struct.JsonGenerator.html Demonstrates serializing a simple string value into a buffer. ```rust use tinyjson::{JsonGenerator, JsonValue}; let v = JsonValue::from("hello, world".to_string()); let mut buf = vec![]; let mut gen = JsonGenerator::new(&mut buf); gen.generate(&v).unwrap(); assert_eq!(String::from_utf8(buf).unwrap(), "\"hello, world\""); ``` -------------------------------- ### JsonValue Usage and Conversion Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html Demonstrates creating a JsonValue, accessing inner data, checking types, and converting back to raw types. ```rust use tinyjson::JsonValue; use std::convert::TryInto; // Convert from raw values using `From` trait let value = JsonValue::from("this is string".to_string()); // Get reference to inner value let maybe_number: Option<&f64> = value.get(); assert!(maybe_number.is_none()); let maybe_string: Option<&String> = value.get(); assert!(maybe_string.is_some()); // Check type of JSON value assert!(matches!(value, JsonValue::String(_))); assert!(value.is_string()); // Convert into raw values using `TryInto` trait let original_value: String = value.try_into().unwrap(); ``` -------------------------------- ### Parse JSON using JsonParser and FromStr Source: https://docs.rs/tinyjson/2.5.1/tinyjson/struct.JsonParser.html Demonstrates manual parsing using the JsonParser struct versus the more idiomatic FromStr implementation. ```rust use tinyjson::{JsonParser, JsonValue}; let mut parser = JsonParser::new("[1, 2, 3]".chars()); let array = parser.parse().unwrap(); // Equivalent to the above code using `FromStr` let array: JsonValue = "[1, 2, 3]".parse().unwrap(); ``` -------------------------------- ### Fallback with or Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Returns the provided result if the current result is Err, otherwise returns the Ok value. ```rust let x: Result = Ok(2); let y: Result = Err("late error"); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("early error"); let y: Result = Ok(2); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("not a 2"); let y: Result = Err("late error"); assert_eq!(x.or(y), Err("late error")); let x: Result = Ok(2); let y: Result = Ok(100); assert_eq!(x.or(y), Ok(2)); ``` -------------------------------- ### Convert Result to reference Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Create a new Result containing references to the original values. ```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")); ``` -------------------------------- ### JsonParser::new Source: https://docs.rs/tinyjson/2.5.1/tinyjson/struct.JsonParser.html Creates a new instance of the JsonParser from an iterator of characters. ```APIDOC ## pub fn new(it: I) -> Self ### Description Creates a new parser instance from an iterator which iterates characters. The iterator is usually built from `str::chars` for parsing `str` or `String` values. ### Parameters - **it** (I: Iterator) - Required - The iterator providing characters to parse. ``` -------------------------------- ### Parse and Generate JSON with tinyjson Source: https://docs.rs/tinyjson Demonstrates parsing a JSON string into a JsonValue, accessing inner data, generating JSON strings, and manipulating values using standard containers. ```rust use tinyjson::JsonValue; use std::collections::HashMap; use std::convert::TryInto; let s = r#" { "bool": true, "arr": [1, null, "test"], "nested": { "blah": false, "blahblah": 3.14 }, "unicode": "\u2764" } "#; // Parse from strings let parsed: JsonValue = s.parse().unwrap(); // Access to inner value represented with standard containers let object: &HashMap<_, _> = parsed.get().unwrap(); println!("Parsed HashMap: {:?}", object); // Generate JSON string println!("{}", parsed.stringify().unwrap()); // Generate formatted JSON string with indent println!("{}", parsed.format().unwrap()); // Convert to inner value represented with standard containers let object: HashMap<_, _> = parsed.try_into().unwrap(); println!("Converted into HashMap: {:?}", object); // Create JSON values from standard containers let mut m = HashMap::new(); m.insert("foo".to_string(), true.into()); let mut v = JsonValue::from(m); // Access with `Index` and `IndexMut` operators quickly println!("{:?}", v["foo"]); v["foo"] = JsonValue::from("hello".to_string()); println!("{:?}", v["foo"]); ``` -------------------------------- ### Convert Result to Option (Ok) Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Extract the success value into an Option. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` -------------------------------- ### Expect a Result value Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Use expect to retrieve the Ok value or panic with a custom message if the result is Err. ```rust let x: Result = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` ``` ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### Chaining Results with and Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Returns the second result if the first is Ok, otherwise returns the Err value of the first. ```rust let x: Result = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); let x: Result = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); let x: Result = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); let x: Result = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); ``` -------------------------------- ### Unwrap with default value Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Returns the contained Ok value or a provided default value. ```rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### Unwrap a Result value Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Use unwrap to retrieve the Ok value, panicking if the result is Err. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` ```rust let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### TryFrom for f64 Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html Attempts to convert a JsonValue into a 64-bit float. Returns an UnexpectedValue error if the underlying type is not a number. ```APIDOC ## fn try_from(v: JsonValue) -> Result ### Description Converts a JsonValue into a 64-bit float. If the JsonValue does not contain a number, an UnexpectedValue error is returned. ### Parameters - **v** (JsonValue) - The value to convert. ### Returns - **Result** - The converted float or an error if the type is incompatible. ``` -------------------------------- ### Using map_or_default on Result Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Maps Ok to a value or returns the default for the type if Err. Requires the nightly-only feature result_option_map_or_default. ```rust #![feature(result_option_map_or_default)] let x: Result<_, &str> = Ok("foo"); let y: Result<&str, _> = Err("bar"); assert_eq!(x.map_or_default(|x| x.len()), 3); assert_eq!(y.map_or_default(|y| y.len()), 0); ``` -------------------------------- ### Index JsonValue with string keys Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html Accesses object values by key. Panics if the value is not an object or the key is missing. ```rust use tinyjson::JsonValue; use std::collections::HashMap; let mut m = HashMap::new(); m.insert("foo".to_string(), 1.0.into()); let v = JsonValue::from(m); let i = &v["foo"]; assert_eq!(i, &JsonValue::Number(1.0)); ``` ```rust let v = JsonValue::from(vec![]); let _ = &v["foo"]; // Panic ``` ```rust let v = JsonValue::from(HashMap::new()); let _ = &v["foo"]; // Panic ``` ```rust let mut json: JsonValue = r#" { "foo": { "bar": [ { "target": 42 } ] } } "#.parse().unwrap(); // Access with index operator let target_value: f64 = *json["foo"]["bar"][0]["target"].get().unwrap(); assert_eq!(target_value, 42.0); ``` -------------------------------- ### Unwrap with closure Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Returns the contained Ok value or computes it from a closure. ```rust fn count(x: &str) -> usize { x.len() } ``` -------------------------------- ### Expect an error Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Use expect_err to retrieve the Err value, panicking if the result is Ok. ```rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### Detecting a JsonParseError Source: https://docs.rs/tinyjson/2.5.1/tinyjson/struct.JsonParseError.html Demonstrates how to catch and verify a parsing error when processing malformed JSON input. ```rust use tinyjson::{JsonParser, JsonParseError}; let error = JsonParser::new("[1, 2, 3".chars()).parse().unwrap_err(); assert!(matches!(error, JsonParseError{..})); ``` -------------------------------- ### Using inspect on Result Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Executes a function with a reference to the Ok value without modifying the result. ```rust let x: u8 = "4" .parse::() .inspect(|x| println!("original: {x}")) .map(|x| x.pow(3)) .expect("failed to parse number"); ``` -------------------------------- ### Check if Result is Ok with predicate Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Verify if a result is Ok and matches a specific condition. ```rust let x: Result = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Collect Result Iterator Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Demonstrates how FromIterator short-circuits when encountering an Err variant. ```rust let v = vec![1, 2]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!") ).collect(); assert_eq!(res, Ok(vec![2, 3])); ``` ```rust let v = vec![1, 2, 0]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!") ).collect(); assert_eq!(res, Err("Underflow!")); ``` ```rust let v = vec![3, 2, 1, 10]; let mut shared = 0; let res: Result, &'static str> = v.iter().map(|x: &u32| { shared += x; x.checked_sub(2).ok_or("Underflow!") }).collect(); assert_eq!(res, Err("Underflow!")); assert_eq!(shared, 6); ``` -------------------------------- ### Check if Result is Ok Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Verify if a result contains a success value. ```rust let x: Result = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` -------------------------------- ### Format JsonValue with indentation Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html Generate a pretty-printed string or write to a stream with 2-space indentation. ```rust use tinyjson::JsonValue; let v = JsonValue::from(vec![1.0.into(), true.into(), "str".to_string().into()]); let s = v.format().unwrap(); assert_eq!(&s, "[ 1, true, \"str\" ]"); ``` ```rust use tinyjson::JsonValue; let v = JsonValue::from(vec![1.0.into(), true.into(), "str".to_string().into()]); let mut bytes = vec![]; v.format_to(&mut bytes).unwrap(); assert_eq!(&String::from_utf8(bytes).unwrap(), "[ 1, true, \"str\" ]"); ``` -------------------------------- ### Unwrap an error Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Use unwrap_err to retrieve the Err value, panicking if the result is Ok. ```rust let x: Result = Ok(2); x.unwrap_err(); // panics with `2` ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### pub fn line(&self) -> usize Source: https://docs.rs/tinyjson/2.5.1/tinyjson/struct.JsonParseError.html Retrieves the 1-based line number where the JSON parse error occurred. ```APIDOC ## pub fn line(&self) -> usize ### Description Returns the 1-based line number where the parse error occurred. ### Returns - **usize** - The line number. ``` -------------------------------- ### JsonGenerator::new Source: https://docs.rs/tinyjson/2.5.1/tinyjson/struct.JsonGenerator.html Creates a new JsonGenerator instance that writes serialized data to the provided io::Write object. ```APIDOC ## pub fn new(out: W) -> Self ### Description Creates a new JsonGenerator object. The serialized byte sequence will be written to the given io::Write object. ### Parameters - **out** (W: Write) - Required - The output stream where the serialized JSON will be written. ``` -------------------------------- ### Handle UnexpectedValue error Source: https://docs.rs/tinyjson/2.5.1/tinyjson/struct.UnexpectedValue.html Demonstrates catching an error when attempting an invalid conversion from JsonValue. ```rust use tinyjson::{JsonValue, UnexpectedValue}; use std::convert::TryFrom; let error = String::try_from(JsonValue::from(1.0)).unwrap_err(); assert!(matches!(error, UnexpectedValue{..})); ``` -------------------------------- ### Index JsonValue with usize Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html Accesses array elements by index. Panics if the value is not an array or the index is out of bounds. ```rust use tinyjson::JsonValue; let v = JsonValue::from(vec![1.0.into(), true.into()]); let b = &v[1]; assert_eq!(b, &JsonValue::Boolean(true)); ``` ```rust use std::collections::HashMap; let v = JsonValue::from(HashMap::new()); let _ = &v[0]; // Panic ``` ```rust let v = JsonValue::from(vec![]); let _ = &v[0]; // Panic ``` -------------------------------- ### Extracting Ok value with into_ok Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Extracts the contained Ok value from a Result. ```rust let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Convert Result to mutable reference Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Create a new Result containing mutable references to the original values. ```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); ``` -------------------------------- ### Unwrap or default value Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Use unwrap_or_default to return the contained value if Ok, or the type's default value if Err. ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### Convert () to JsonValue Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html Converts the unit type () into a null JsonValue. ```rust use tinyjson::JsonValue; let v = JsonValue::from(()); assert!(v.is_null()); ``` -------------------------------- ### Convert JsonValue to f64 Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html Attempts to convert a JsonValue into a 64-bit float, returning an error if the underlying type is not a number. ```rust use tinyjson::JsonValue; use std::convert::TryFrom; let v = JsonValue::from(1.0); let r = f64::try_from(v); assert!(r.is_ok()); let v = JsonValue::from(true); let r = f64::try_from(v); assert!(r.is_err()); ``` -------------------------------- ### Using iter on Result Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Returns an iterator that yields the contained value if Ok, or nothing if 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); ``` -------------------------------- ### Using map_or on Result Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Returns a default value if Err, or applies a function to the Ok value. Note that arguments are eagerly evaluated. ```rust let x: Result<_, &str> = Ok("foo"); assert_eq!(x.map_or(42, |v| v.len()), 3); let x: Result<&str, _> = Err("bar"); assert_eq!(x.map_or(42, |v| v.len()), 42); ``` -------------------------------- ### pub fn column(&self) -> usize Source: https://docs.rs/tinyjson/2.5.1/tinyjson/struct.JsonParseError.html Retrieves the 1-based column number where the JSON parse error occurred. ```APIDOC ## pub fn column(&self) -> usize ### Description Returns the 1-based column number where the parse error occurred. ### Returns - **usize** - The column number. ``` -------------------------------- ### TryFrom Conversions for JsonValue Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html Convert JsonValue instances into native Rust types. These operations return an UnexpectedValue error if the underlying JSON type does not match the target type. ```rust use tinyjson::JsonValue; use std::convert::TryFrom; let v = JsonValue::from(()); let r = <()>::try_from(v); assert!(r.is_ok()); let v = JsonValue::from(1.0); let r = <()>::try_from(v); assert!(r.is_err()); ``` ```rust use tinyjson::JsonValue; use std::convert::TryFrom; use std::collections::HashMap; let mut m = HashMap::new(); m.insert("foo".to_string(), 42.0.into()); let v = JsonValue::from(m); let r = >::try_from(v); assert!(r.is_ok()); let v = JsonValue::from(1.0); let r = >::try_from(v); assert!(r.is_err()); ``` ```rust use tinyjson::JsonValue; use std::convert::TryFrom; let v = JsonValue::from("foo".to_string()); let r = String::try_from(v); assert!(r.is_ok()); let v = JsonValue::from(1.0); let r = String::try_from(v); assert!(r.is_err()); ``` ```rust use tinyjson::JsonValue; use std::convert::TryFrom; let v = JsonValue::from(vec![true.into()]); let r = >::try_from(v); assert!(r.is_ok()); let v = JsonValue::from(1.0); let r = >::try_from(v); assert!(r.is_err()); ``` -------------------------------- ### JsonGenerator::indent Source: https://docs.rs/tinyjson/2.5.1/tinyjson/struct.JsonGenerator.html Configures the indentation string used for formatting the serialized JSON output. ```APIDOC ## pub fn indent(self, indent: &'indent str) -> Self ### Description Sets the indent string. This will be used by JsonGenerator::generate to format the output. ### Parameters - **indent** (&'indent str) - Required - The string used for indentation (e.g., " " or "\t"). ``` -------------------------------- ### Convert f64 to JsonValue Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html Converts a 64-bit float into a JsonValue number. ```rust use tinyjson::JsonValue; let v = JsonValue::from(1.0); assert!(v.is_number()); ``` -------------------------------- ### Chaining Results with and_then Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Calls a function if the result is Ok, otherwise returns the Err value. Useful for chaining fallible operations. ```rust fn sq_then_to_string(x: u32) -> Result { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } assert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string())); assert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err("overflowed")); assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number")); ``` ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Check if Result is Err Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Verify if a result contains an error. ```rust let x: Result = Ok(-3); assert_eq!(x.is_err(), false); let x: Result = Err("Some error message"); assert_eq!(x.is_err(), true); ``` -------------------------------- ### Using map_or_else on Result Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Maps a Result to a value by applying a fallback function to Err or a mapping function to Ok. Useful for lazy evaluation. ```rust let k = 21; let x : Result<_, &str> = Ok("foo"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3); let x : Result<&str, _> = Err("bar"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42); ``` -------------------------------- ### Write JsonValue to writer Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html Write the JSON representation directly to an object implementing io::Write. ```rust use tinyjson::JsonValue; use std::io::Write; let v = JsonValue::from(vec![1.0.into(), true.into(), "str".to_string().into()]); let mut bytes = vec![]; v.write_to(&mut bytes).unwrap(); assert_eq!(&String::from_utf8(bytes).unwrap(), "[1,true,\"str\"]"); ``` -------------------------------- ### Map Result value Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Apply a function to the success value of a Result. ```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(..) => {} } } ``` -------------------------------- ### Parse string to JsonValue Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html Parses a string slice into a JsonValue using FromStr. ```rust use tinyjson::JsonValue; let array: JsonValue = "[1, 2, 3]".parse().unwrap(); assert!(array.is_array()); ``` -------------------------------- ### Serialize JsonValue to String Source: https://docs.rs/tinyjson/2.5.1/tinyjson/fn.stringify.html Converts a JsonValue into a compact JSON string representation. ```rust use tinyjson::JsonValue; let v = JsonValue::from(vec![1.0.into(), 2.0.into(), 3.0.into()]); let s = tinyjson::stringify(&v).unwrap(); assert_eq!(s, "[1,2,3]"); ``` -------------------------------- ### pub fn format(value: &JsonValue) -> JsonGenerateResult Source: https://docs.rs/tinyjson/2.5.1/tinyjson/fn.format.html Serializes the given JsonValue to a String with 2-spaces indentation. This function is functionally equivalent to JsonValue::format. ```APIDOC ## pub fn format(value: &JsonValue) -> JsonGenerateResult ### Description Serializes the given `JsonValue` value to `String` with 2-spaces indentation. This method is almost identical to `JsonValue::format` but exists for a historical reason. ### Parameters - **value** (&JsonValue) - Required - The JSON value to serialize. ### Returns - **JsonGenerateResult** - The result of the serialization process. ### Example ```rust use tinyjson::JsonValue; let v = JsonValue::from(vec![1.0.into(), 2.0.into(), 3.0.into()]); let s = tinyjson::format(&v).unwrap(); assert_eq!(s, "[\n 1,\n 2,\n 3\n]"); ``` ``` -------------------------------- ### Check JsonValue type Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html Use the is_* methods to verify the underlying type of a JsonValue instance. ```rust use tinyjson::JsonValue; let v = JsonValue::from(true); assert!(v.is_bool()); let v = JsonValue::from(1.0); assert!(!v.is_bool()); ``` ```rust use tinyjson::JsonValue; let v = JsonValue::from(1.0); assert!(v.is_number()); let v = JsonValue::from(false); assert!(!v.is_number()); ``` ```rust use tinyjson::JsonValue; let v = JsonValue::from("foo".to_string()); assert!(v.is_string()); let v = JsonValue::from(1.0); assert!(!v.is_string()); ``` ```rust use tinyjson::JsonValue; let v = JsonValue::from(()); // () is inner representation of null value assert!(v.is_null()); let v = JsonValue::from(false); assert!(!v.is_null()); ``` ```rust use tinyjson::JsonValue; let v = JsonValue::from(vec![]); assert!(v.is_array()); let v = JsonValue::from(1.0); assert!(!v.is_array()); ``` ```rust use tinyjson::JsonValue; use std::collections::HashMap; let v = JsonValue::from(HashMap::new()); assert!(v.is_object()); let v = JsonValue::from(vec![]); assert!(!v.is_object()); ``` -------------------------------- ### Using as_deref on Result Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Converts a Result to a Result containing references to the dereferenced target. ```rust let x: Result = Ok("hello".to_string()); let y: Result<&str, &u32> = Ok("hello"); assert_eq!(x.as_deref(), y); let x: Result = Err(42); let y: Result<&str, &u32> = Err(&42); assert_eq!(x.as_deref(), y); ``` -------------------------------- ### Convert String to JsonValue Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html Converts a String into a JsonValue. Note that &str is not supported directly. ```rust use tinyjson::JsonValue; let v = JsonValue::from("foo".to_string()); assert!(v.is_string()); ``` -------------------------------- ### Convert Result to Option (Err) Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Extract the error value into an Option. ```rust let x: Result = Ok(2); assert_eq!(x.err(), None); let x: Result = Err("Nothing here"); assert_eq!(x.err(), Some("Nothing here")); ``` -------------------------------- ### Serialize JsonValue to String Source: https://docs.rs/tinyjson/2.5.1/tinyjson/fn.format.html Serializes a JsonValue into a string with 2-space indentation. This function is functionally equivalent to JsonValue::format. ```rust use tinyjson::JsonValue; let v = JsonValue::from(vec![1.0.into(), 2.0.into(), 3.0.into()]); let s = tinyjson::format(&v).unwrap(); assert_eq!(s, "[\n 1,\n 2,\n 3\n]"); ``` -------------------------------- ### TryFrom for bool Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html Attempts to convert a JsonValue into a boolean. Returns an UnexpectedValue error if the underlying type is not a boolean. ```APIDOC ## fn try_from(v: JsonValue) -> Result ### Description Converts a JsonValue into a boolean. If the JsonValue does not contain a boolean, an UnexpectedValue error is returned. ### Parameters - **v** (JsonValue) - The value to convert. ### Returns - **Result** - The converted boolean or an error if the type is incompatible. ``` -------------------------------- ### JsonGenerator::generate Source: https://docs.rs/tinyjson/2.5.1/tinyjson/struct.JsonGenerator.html Serializes a JsonValue into the output stream, applying indentation if configured. ```APIDOC ## pub fn generate(&mut self, value: &JsonValue) -> Result<()> ### Description Serializes the JsonValue into a UTF-8 byte sequence. The result is written to the io::Write object provided during initialization. If an indent string was set, it will be used for elements of arrays and objects. ### Parameters - **value** (&JsonValue) - Required - The JSON value to serialize. ``` -------------------------------- ### Check if Result is Err with predicate Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Verify if a result is Err and matches a specific condition. ```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); ``` -------------------------------- ### Define JsonParser struct Source: https://docs.rs/tinyjson/2.5.1/tinyjson/struct.JsonParser.html The internal structure definition for JsonParser, which requires an iterator over characters. ```rust pub struct JsonParser where I: Iterator, { /* private fields */ } ``` -------------------------------- ### JsonParseResult Definition Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonParseResult.html The type alias and its enum representation. ```rust pub type JsonParseResult = Result; ``` ```rust pub enum JsonParseResult { Ok(JsonValue), Err(JsonParseError), } ``` -------------------------------- ### pub unsafe fn unwrap_unchecked(self) -> T Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Returns the contained Ok value, consuming the self value, without checking that the value is not an Err. Calling this method on an Err is undefined behavior. ```APIDOC ## pub unsafe fn unwrap_unchecked(self) -> T ### Description Returns the contained `Ok` value, consuming the `self` value, without checking that the value is not an `Err`. ### Safety Calling this method on an `Err` is _undefined behavior_. ``` -------------------------------- ### Fallback with or_else Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Calls a closure to compute a fallback result if the current result is Err. ```rust fn sq(x: u32) -> Result { Ok(x * x) } fn err(x: u32) -> Result { Err(x) } assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2)); assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2)); assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9)); assert_eq!(Err(3).or_else(err).or_else(err), Err(3)); ``` -------------------------------- ### Convert HashMap to JsonValue Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html Converts a HashMap into a JsonValue object. ```rust use tinyjson::JsonValue; use std::collections::HashMap; let mut m = HashMap::new(); m.insert("foo".to_string(), 1.0.into()); let v = JsonValue::from(m); assert!(v.is_object()); ``` -------------------------------- ### stringify(value: &JsonValue) -> JsonGenerateResult Source: https://docs.rs/tinyjson/2.5.1/tinyjson/fn.stringify.html Serializes the provided JsonValue into a String without indentation. This function is functionally equivalent to JsonValue::stringify. ```APIDOC ## Function: stringify ### Description Serializes the given `JsonValue` to a `String` without indentation. This method is provided for historical compatibility and behaves identically to `JsonValue::stringify`. ### Signature `pub fn stringify(value: &JsonValue) -> JsonGenerateResult` ### Parameters - **value** (&JsonValue) - Required - The JSON value to be serialized. ### Returns - **JsonGenerateResult** - The result of the serialization process. ### Example ```rust use tinyjson::JsonValue; let v = JsonValue::from(vec![1.0.into(), 2.0.into(), 3.0.into()]); let s = tinyjson::stringify(&v).unwrap(); assert_eq!(s, "[1,2,3]"); ``` ``` -------------------------------- ### UnexpectedValue::value Source: https://docs.rs/tinyjson/2.5.1/tinyjson/struct.UnexpectedValue.html Retrieves a reference to the JsonValue that failed the conversion process. ```APIDOC ## pub fn value(&self) -> &JsonValue ### Description Returns a reference to the JsonValue that caused the conversion error. ### Returns - **&JsonValue** - A reference to the original value that failed to be converted. ``` -------------------------------- ### Access failed value Source: https://docs.rs/tinyjson/2.5.1/tinyjson/struct.UnexpectedValue.html Retrieves the original JsonValue that caused the conversion error. ```rust use tinyjson::JsonValue; use std::convert::TryFrom; let error = String::try_from(JsonValue::from(1.0)).unwrap_err(); assert_eq!(error.value(), &JsonValue::Number(1.0)); ``` -------------------------------- ### Result IntoIterator Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Consuming iterator that yields the contained value if Ok, or nothing if Err. ```rust let x: Result = Ok(5); let v: Vec = x.into_iter().collect(); assert_eq!(v, [5]); let x: Result = Err("nothing!"); let v: Vec = x.into_iter().collect(); assert_eq!(v, []); ``` -------------------------------- ### Define JsonGenerateResult Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html The type alias definition for serialization results. ```rust pub type JsonGenerateResult = Result; ``` -------------------------------- ### Define UnexpectedValue struct Source: https://docs.rs/tinyjson/2.5.1/tinyjson/struct.UnexpectedValue.html The definition of the UnexpectedValue struct. ```rust pub struct UnexpectedValue { /* private fields */ } ``` -------------------------------- ### pub unsafe fn unwrap_err_unchecked(self) -> E Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Returns the contained Err value, consuming the self value, without checking that the value is not an Ok. Calling this method on an Ok is undefined behavior. ```APIDOC ## pub unsafe fn unwrap_err_unchecked(self) -> E ### Description Returns the contained `Err` value, consuming the `self` value, without checking that the value is not an `Ok`. ### Safety Calling this method on an `Ok` is _undefined behavior_. ``` -------------------------------- ### Calculate Product of Result Iterator Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Multiplies elements in an iterator of Results, returning the first Err encountered or the product of all Ok values. ```rust let nums = vec!["5", "10", "1", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert_eq!(total, Ok(100)); let nums = vec!["5", "10", "one", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert!(total.is_err()); ``` -------------------------------- ### Convert bool to JsonValue Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html Converts a boolean into a JsonValue. ```rust use tinyjson::JsonValue; let v = JsonValue::from(true); assert!(v.is_bool()); ``` -------------------------------- ### JsonParser::parse Source: https://docs.rs/tinyjson/2.5.1/tinyjson/struct.JsonParser.html Executes the parsing process to extract a single JSON value from the iterator. ```APIDOC ## pub fn parse(&mut self) -> JsonParseResult ### Description Run the parser to parse one JSON value. ``` -------------------------------- ### Convert error to JsonValue Source: https://docs.rs/tinyjson/2.5.1/tinyjson/struct.UnexpectedValue.html Converts an UnexpectedValue error back into the original JsonValue. ```rust use tinyjson::JsonValue; use std::convert::TryFrom; let error = String::try_from(JsonValue::from(1.0)).unwrap_err(); assert_eq!(JsonValue::from(error), JsonValue::Number(1.0)); ``` -------------------------------- ### Using as_deref_mut on Result Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Converts a Result to a Result containing mutable references to the dereferenced target. ```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); ``` -------------------------------- ### Calculate Sum of Result Iterator Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Sums elements in an iterator of Results, returning the first Err encountered or the sum of all Ok values. ```rust let f = |&x: &i32| if x < 0 { Err("Negative element found") } else { Ok(x) }; let v = vec![1, 2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Ok(3)); let v = vec![1, -2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Err("Negative element found")); ``` -------------------------------- ### JsonValue Definition Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html The structure of the JsonValue enum showing all supported JSON variants. ```rust pub enum JsonValue { Number(f64), Boolean(bool), String(String), Null, Array(Vec), Object(HashMap), } ``` -------------------------------- ### Extracting Err value with into_err Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Extracts the contained Err value without panicking. This is a nightly-only experimental API. ```rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### JsonValue::format Source: https://docs.rs/tinyjson Serializes a JsonValue into a formatted JSON string with 2-space indentation. ```APIDOC ## JsonValue::format ### Description Serializes the `JsonValue` into a human-readable JSON string with 2-space indentation. ### Signature `fn format(&self) -> Result` ``` -------------------------------- ### Retrieving Error Location Source: https://docs.rs/tinyjson/2.5.1/tinyjson/struct.JsonParseError.html Methods to extract the line and column numbers of a parsing error, both of which are 1-based. ```rust use tinyjson::{JsonParser, JsonParseError}; let error = JsonParser::new("[1, 2, 3".chars()).parse().unwrap_err(); assert_eq!(error.line(), 1); ``` ```rust use tinyjson::{JsonParser, JsonParseError}; let error = JsonParser::new("[1, 2, 3".chars()).parse().unwrap_err(); assert_eq!(error.column(), 8); ``` -------------------------------- ### Mutable Indexing for JsonValue Objects Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html Access and modify values within a JSON object using string keys. Note that these operations will panic if the value is not an object or if the key is missing. ```rust use tinyjson::JsonValue; use std::collections::HashMap; let mut m = HashMap::new(); m.insert("foo".to_string(), 1.0.into()); let mut v = JsonValue::from(m); v["foo"] = JsonValue::Number(3.14); assert_eq!(v["foo"], JsonValue::Number(3.14)); ``` ```rust let mut v = JsonValue::from(vec![]); let _ = &mut v["foo"]; // Panic ``` ```rust let mut v = JsonValue::from(HashMap::new()); let _ = &mut v["foo"]; // Panic ``` ```rust let mut json: JsonValue = r#" { "foo": { "bar": [ { "target": 42 } ] } } "#.parse().unwrap(); // Modify with index operator json["foo"]["bar"][0]["target"] = JsonValue::Boolean(false); assert_eq!(json["foo"]["bar"][0]["target"], JsonValue::Boolean(false)); ``` -------------------------------- ### Convert Vec to JsonValue Source: https://docs.rs/tinyjson/2.5.1/tinyjson/enum.JsonValue.html Converts a Vec of JsonValue into a JsonValue array. ```rust use tinyjson::JsonValue; let v = JsonValue::from(vec![1.0.into(), true.into()]); assert!(v.is_array()); ``` -------------------------------- ### InnerAsRefMut Trait Definition Source: https://docs.rs/tinyjson/2.5.1/tinyjson/trait.InnerAsRefMut.html The core trait definition requiring the implementation of json_value_as_mut. ```rust pub trait InnerAsRefMut { // Required method fn json_value_as_mut(v: &mut JsonValue) -> Option<&mut Self>; } ``` -------------------------------- ### Using map_err on Result Source: https://docs.rs/tinyjson/2.5.1/tinyjson/type.JsonGenerateResult.html Maps the Err variant of a Result while leaving the Ok variant untouched. ```rust fn stringify(x: u32) -> String { format!("error code: {x}") } let x: Result = Ok(2); assert_eq!(x.map_err(stringify), Ok(2)); let x: Result = Err(13); assert_eq!(x.map_err(stringify), Err("error code: 13".to_string())); ``` -------------------------------- ### JsonValue::format Source: https://docs.rs/tinyjson/2.5.1/tinyjson/index.html Serializes a JsonValue into a formatted JSON string with indentation. ```APIDOC ## JsonValue::format ### Description Serializes the `JsonValue` into a human-readable JSON string with 2-space indentation. ### Usage ```rust let formatted_str = parsed.format().unwrap(); ``` ```