pub trait ValueReader<J: JsonReader> {
Show 16 methods // Required methods fn peek_value(&mut self) -> Result<ValueType, ReaderError>; fn read_null(self) -> Result<(), ReaderError>; fn read_bool(self) -> Result<bool, ReaderError>; fn read_str<T>( self, f: impl FnOnce(&str) -> Result<T, Box<dyn Error>> ) -> Result<T, Box<dyn Error>>; fn read_string(self) -> Result<String, ReaderError>; fn read_string_with_reader<T>( self, f: impl FnOnce(StringValueReader<'_>) -> Result<T, Box<dyn Error>> ) -> Result<T, Box<dyn Error>>; fn read_number<T: FromStr>(self) -> Result<Result<T, T::Err>, ReaderError>; fn read_number_as_string(self) -> Result<String, ReaderError>; fn read_deserialize<'de, D: Deserialize<'de>>( self ) -> Result<D, DeserializerError>; fn skip_value(self) -> Result<(), ReaderError>; fn read_array<T>( self, f: impl FnOnce(&mut ArrayReader<'_, J>) -> Result<T, Box<dyn Error>> ) -> Result<T, Box<dyn Error>>; fn read_object_borrowed_names( self, f: impl FnMut(MemberReader<'_, J>) -> Result<(), Box<dyn Error>> ) -> Result<(), Box<dyn Error>>; fn read_object_owned_names( self, f: impl FnMut(String, SingleValueReader<'_, J>) -> Result<(), Box<dyn Error>> ) -> Result<(), Box<dyn Error>>; fn read_seeked<T>( self, path: &JsonPath, f: impl FnOnce(SingleValueReader<'_, J>) -> Result<T, Box<dyn Error>> ) -> Result<T, Box<dyn Error>>; fn read_seeked_multi( self, path: &MultiJsonPath, at_least_one_match: bool, f: impl FnMut(SingleValueReader<'_, J>) -> Result<(), Box<dyn Error>> ) -> Result<(), Box<dyn Error>>; // Provided method fn read_array_items( self, f: impl FnMut(SingleValueReader<'_, J>) -> Result<(), Box<dyn Error>> ) -> Result<(), Box<dyn Error>> where Self: Sized { ... }
}
Available on crate feature experimental only.
Expand description

Reader for a JSON value

Required Methods§

source

fn peek_value(&mut self) -> Result<ValueType, ReaderError>

Peeks at the type of the next JSON value, without consuming it

source

fn read_null(self) -> Result<(), ReaderError>

Consumes a JSON null value

source

fn read_bool(self) -> Result<bool, ReaderError>

Consumes and returns a JSON boolean value

source

fn read_str<T>( self, f: impl FnOnce(&str) -> Result<T, Box<dyn Error>> ) -> Result<T, Box<dyn Error>>

Consumes a JSON string value as borrowed str

The function f is called with the read JSON string value as argument.

To read a string value as owned String use read_string.
To read a large string value in a streaming way, use read_string_with_reader.

source

fn read_string(self) -> Result<String, ReaderError>

Consumes and returns a JSON string value as owned String

To read a string value as borrowed str use read_str.
To read a large string value in a streaming way, use read_string_with_reader.

source

fn read_string_with_reader<T>( self, f: impl FnOnce(StringValueReader<'_>) -> Result<T, Box<dyn Error>> ) -> Result<T, Box<dyn Error>>

Consumes a JSON string using a Read

The function f is called with a reader as argument which allows reading the JSON string value. Escape sequences will be automatically converted to the corresponding characters. If the function returns Ok but did not consume all bytes of the string value, the remaining bytes will be skipped automatically.

This method is mainly intended for reading large JSON string values in a streaming way; for short string values prefer read_str or read_string.

§Examples
let json_reader = SimpleJsonReader::new("\"text with \\\" quote\"".as_bytes());
json_reader.read_string_with_reader(|mut string_reader| {
    let mut buf = [0_u8; 1];
    while string_reader.read(&mut buf)? > 0 {
        println!("Read byte: {}", buf[0]);
    }
    Ok(())
})?;
§Reader errors

The error behavior of the string reader differs from the guarantees made by Read:

  • if an error is returned there are no guarantees about if or how many data has been consumed from the underlying data source and been stored in the provided buf
  • if an error occurs, processing should be aborted, regardless of the kind of the error; trying to use the string reader or the original JSON reader afterwards will lead to unspecified behavior
source

fn read_number<T: FromStr>(self) -> Result<Result<T, T::Err>, ReaderError>

Consumes and returns a JSON number value

The result is either the parsed number or the parse error. It might be necessary to help the Rust compiler a bit by explicitly specifying the number type in case it cannot be inferred automatically.

§Examples
let json_reader = SimpleJsonReader::new("12".as_bytes());
let number: u64 = json_reader.read_number()??;
assert_eq!(number, 12);
source

fn read_number_as_string(self) -> Result<String, ReaderError>

Consumes and returns the string representation of a JSON number value

§Examples
let json_reader = SimpleJsonReader::new("1.2e3".as_bytes());
let number_string = json_reader.read_number_as_string()?;
assert_eq!(number_string, "1.2e3");
source

fn read_deserialize<'de, D: Deserialize<'de>>( self ) -> Result<D, DeserializerError>

Available on crate feature serde only.

Deserializes a Serde Deserialize from the next value

This method is part of the optional Serde integration feature, see the serde module of this crate for more information.

§Examples
let json_reader = SimpleJsonReader::new(
    r#"{"text": "some text", "number": 5}"#.as_bytes()
);

#[derive(Deserialize, PartialEq, Debug)]
struct MyStruct {
    text: String,
    number: u64,
}

let value: MyStruct = json_reader.read_deserialize()?;
assert_eq!(
    value,
    MyStruct { text: "some text".to_owned(), number: 5 }
);
§Security

Since JSON data can have an arbitrary structure and can contain arbitrary data, care must be taken when processing untrusted data. See the documentation of JsonReaderDeserializer for security considerations.

source

fn skip_value(self) -> Result<(), ReaderError>

Skips the next JSON value

If the value is a JSON array or object, all the nested values will be skipped as well. This method is usually more efficient than reading the next JSON value using one of the other methods, but discarding the read result afterwards.

source

fn read_array<T>( self, f: impl FnOnce(&mut ArrayReader<'_, J>) -> Result<T, Box<dyn Error>> ) -> Result<T, Box<dyn Error>>

Consumes a JSON array

This method is useful when arrays of fixed size or with heterogenous item types are read; otherwise prefer read_array_items.

If the exact size is not known in advance, ArrayReader::has_next can be used to check if there are more items in the JSON array. If the value types are not known in advance, ArrayReader::peek_value can be used to peek at the next item (optionally calling has_next before to make sure there is actually a next item).

If the function f returns Ok it must have consumed all array items, either by reading them or by calling ArrayReader::skip_value until there are no more items (can be checked using ArrayReader::has_next). Otherwise an error is returned.

§Examples
let json_reader = SimpleJsonReader::new("[1, 2, 3]".as_bytes());
let point: (u64, u64, u64) = json_reader.read_array(|array_reader| {
    let x = array_reader.read_number()??;
    let y = array_reader.read_number()??;
    let z = array_reader.read_number()??;
    Ok((x, y, z))
})?;
assert_eq!(point, (1, 2, 3));
source

fn read_object_borrowed_names( self, f: impl FnMut(MemberReader<'_, J>) -> Result<(), Box<dyn Error>> ) -> Result<(), Box<dyn Error>>

Consumes a JSON object and all of its members, reading names as borrowed str

The function f is called repeatedly for all members of the JSON object, if any. It takes a MemberReader as argument which allows reading the name and the value of the member.

If the function returns Ok but did not read the name or the value of the member, then name or value will be skipped automatically.

If the name is needed as owned String, then read_object_owned_names should be used instead.

§Examples
let json_reader = SimpleJsonReader::new(r#"{"a": 1, "b": 2}"#.as_bytes());

let mut a: Option<u32> = None;
json_reader.read_object_borrowed_names(|mut member_reader| {
    let name = member_reader.read_name()?;
    match name {
        "a" => a = Some(member_reader.read_number()??),
        _ => {
            // ignore member value
        }
    }
    Ok(())
})?;
println!("a = {a:?}");
source

fn read_object_owned_names( self, f: impl FnMut(String, SingleValueReader<'_, J>) -> Result<(), Box<dyn Error>> ) -> Result<(), Box<dyn Error>>

Consumes a JSON object and all of its members, reading names as owned String

The function f is called repeatedly for all members of the JSON object, if any. It takes the member name as first argument and a SingleValueReader for reading the member value as second argument.

If the function returns Ok but did not consume the value of the member, either by reading it (e.g. using read_bool) or by using skip_value, the value will be skipped automatically.

If it suffices to have the name as borrowed str, then read_object_borrowed_names should be used instead.

§Examples
let json_reader = SimpleJsonReader::new(r#"{"a": 1, "b": 2}"#.as_bytes());
let mut map = HashMap::<String, u64>::new();
json_reader.read_object_owned_names(|name, value_reader| {
    let member_value = value_reader.read_number()??;
    map.insert(name, member_value);
    Ok(())
})?;

assert_eq!(
    map,
    HashMap::from([
        ("a".to_owned(), 1),
        ("b".to_owned(), 2),
    ])
);
source

fn read_seeked<T>( self, path: &JsonPath, f: impl FnOnce(SingleValueReader<'_, J>) -> Result<T, Box<dyn Error>> ) -> Result<T, Box<dyn Error>>

Seeks to a value and consumes it

This method first seeks to the location specified by path as described by SimpleJsonReader::seek_to, then calls the function f to consume the value.

If the path matches a value, the function f will be called exactly once. Otherwise, if the structure of the JSON data does not match the path, for example when the JSON data contains an array but the path expects an object, an error is returned and f is not called.

If the function f returns Ok but did not consume the value, it will be skipped automatically. After the function has been called this method traverses back to the original nesting level, therefore acting as if it only consumed one value (and its nested values) at that level.

For seeking to and reading multiple values use read_seeked_multi.

§Examples
let json_reader = SimpleJsonReader::new(
    r#"[{"bar": true, "foo": ["a", "b", "c"]}, "next"]"#.as_bytes()
);

json_reader.read_array(|array_reader| {
    // First seek to the "foo" member, then within its value seek to the item at index 1
    array_reader.read_seeked(&json_path!["foo", 1], |value_reader| {
        // Read the value where the reader seeked to
        assert_eq!(value_reader.read_string()?, "b");
        Ok(())
    })?;
     
    // Afterwards can continue reading at original nesting level
    assert_eq!(array_reader.read_string()?, "next");
    Ok(())
})?;
source

fn read_seeked_multi( self, path: &MultiJsonPath, at_least_one_match: bool, f: impl FnMut(SingleValueReader<'_, J>) -> Result<(), Box<dyn Error>> ) -> Result<(), Box<dyn Error>>

Seeks to multiple values and consumes them

Based on the given path this method seeks to all matching values, if any, and calls the function f repeatedly for reading each value. If the function returns Ok but did not consume the value, it will be skipped automatically.

Depending on what pieces the path consists of, it can match any number of values, including none. The at_least_one_match argument determines the behavior of this method in case the path matches no values. If true an error is returned; this can for example be useful when a JSON object member is optional but for multiple of such objects at least one is expected to have the member. If false no error is returned but f is also not called. This does not override the behavior for path pieces which themself require at least one match, such as AllArrayItems { allow_empty: false }.

For ObjectMember and OptionalObjectMember pieces if multiple members in a JSON object have the same name (for example {"a": 1, "a": 2}) this method will only seek to the first occurrence in that object ignoring the others.

Once this method returns, the reader is at the original nesting level again and can continue consuming values there. Calling this method therefore acts as if it only consumed one value (and its nested values) at the that level.

If the structure of the JSON data does not match the path, for example the JSON data contains an array but the path expects an object, an error is returned.

For seeking to and reading a single value at a fixed path prefer read_seeked.

§Examples
let json = r#"{
    "users": [
        {"name": "John", "age": 32},
        {"name": "Jane", "age": 41}
    ]
}"#;
let json_reader = SimpleJsonReader::new(json.as_bytes());

let mut ages = Vec::<u32>::new();
// Select the ages of all users
let json_path = multi_json_path!["users", [*], "age"];
json_reader.read_seeked_multi(&json_path, false, |value_reader| {
    let age = value_reader.read_number()??;
    ages.push(age);
    Ok(())
})?;
assert_eq!(ages, vec![32, 41]);

Provided Methods§

source

fn read_array_items( self, f: impl FnMut(SingleValueReader<'_, J>) -> Result<(), Box<dyn Error>> ) -> Result<(), Box<dyn Error>>
where Self: Sized,

Consumes a JSON array and all of its items

This method is useful when arrays with varying size and homogenous item type are read; otherwise prefer read_array.

The function f is called repeatedly for all items of the JSON array, if any.

If the function returns Ok but did not consume the array item, either by reading it (e.g. using read_bool) or by using skip_value, the item will be skipped automatically.

§Examples
let json_reader = SimpleJsonReader::new(r#"["a", "short", "example"]"#.as_bytes());
let mut words = Vec::<String>::new();
json_reader.read_array_items(|item_reader| {
    let word = item_reader.read_string()?;
    words.push(word);
    Ok(())
})?;
assert_eq!(words, vec!["a", "short", "example"]);

Object Safety§

This trait is not object safe.

Implementors§

source§

impl<J: JsonReader> ValueReader<J> for &mut ArrayReader<'_, J>

source§

impl<J: JsonReader> ValueReader<J> for MemberReader<'_, J>

The ValueReader methods read the member value

source§

impl<J: JsonReader> ValueReader<J> for SimpleJsonReader<J>

source§

impl<J: JsonReader> ValueReader<J> for SingleValueReader<'_, J>