Skip to main content

ObjectReader

Struct ObjectReader 

Source
pub struct ObjectReader<'r, 'de> { /* private fields */ }
Expand description

Reads the members of an object one by one; from Reader::read_object.

Call next_key until it returns None; after each key, read its value with field, value, value_with, raw, or skip, or do nothing and the next next_key skips it. Errors in a value get the member’s key in their path. See FromJson for the whole pattern.

Implementations§

Source§

impl<'de> ObjectReader<'_, 'de>

Source

pub fn next_key(&mut self) -> Result<Option<Cow<'de, str>>, DecodeError>

The next member’s key (borrowed from the input unless it had escapes), or None after the last member, when the object’s } has been read. A value left unread is skipped first (and validated).

§Errors

Any error of the reader, including a repeated key under DuplicateKeys::Error (reported when the object closes).

§Examples
let mut r = jsonx_lib::Reader::new(r#"{"a": [1, 2], "b": 3}"#);
let mut o = r.read_object()?;
assert_eq!(o.next_key()?.as_deref(), Some("a"));
assert_eq!(o.next_key()?.as_deref(), Some("b")); // `[1, 2]` skipped
assert_eq!(o.value::<u8>()?, 3);
assert_eq!(o.next_key()?, None);
Source

pub fn value<T: FromJson<'de>>(&mut self) -> Result<T, DecodeError>

Reads the current member’s value as a T.

§Errors

The DecodeError of T, with this member’s key in its path.

§Examples
let mut r = jsonx_lib::Reader::new(r#"{"n": "x"}"#);
let mut o = r.read_object()?;
o.next_key()?;
assert_eq!(o.value::<u8>().unwrap_err().pointer(), "/n");
Source

pub fn value_with<T>( &mut self, read: impl FnOnce(&mut Reader<'de>) -> Result<T, DecodeError>, ) -> Result<T, DecodeError>

Reads the current member’s value with read, for a value that needs more than a type (a choice of shapes, a value read in place). Errors get the key in their path.

§Errors

Whatever read returns, with this member’s key in its path.

§Examples
let mut r = jsonx_lib::Reader::new(r#"{"n": [1, 2, 3]}"#);
let mut o = r.read_object()?;
o.next_key()?;
let count = o.value_with(|r| {
    let mut items = r.read_array()?;
    let mut count = 0;
    while items.skip()? {
        count += 1;
    }
    Ok(count)
})?;
assert_eq!(count, 3);
Source

pub fn field<T: FromJson<'de>>( &mut self, slot: &mut Option<T>, ) -> Result<(), DecodeError>

Reads the current member’s value into slot, the pattern for a struct field: refused as DecodeErrorKind::DuplicateField (at the key) if slot already holds a value, so a second value for a field cannot override the first. Under DuplicateKeys::First the second value is skipped instead, under Last and KeepAll it replaces the first.

§Errors

DecodeErrorKind::DuplicateField, or the DecodeError of T, with this member’s key in the path.

§Examples
use jsonx_lib::DecodeErrorKind;

let mut r = jsonx_lib::Reader::new(r#"{"id": 1, "id": 2}"#);
let mut o = r.read_object()?;
let mut id: Option<u8> = None;
o.next_key()?;
o.field(&mut id)?;
o.next_key()?;
let err = o.field(&mut id).unwrap_err();
assert_eq!((err.kind(), err.offset(), err.pointer()), (&DecodeErrorKind::DuplicateField, 10, "/id".into()));
Source

pub fn skip(&mut self) -> Result<(), DecodeError>

Skips the current member’s value, validating it.

§Errors

Any error of the reader inside the value.

§Examples
let mut r = jsonx_lib::Reader::new(r#"{"big": [[1], {}], "n": 1}"#);
let mut o = r.read_object()?;
o.next_key()?;
o.skip()?;
assert_eq!(o.next_key()?.as_deref(), Some("n"));
Source

pub fn raw(&mut self) -> Result<&'de str, DecodeError>

The current member’s value as its exact source text, validated.

§Errors

Any error of the reader inside the value.

§Examples
let mut r = jsonx_lib::Reader::new(r#"{"params": {"line": 3}}"#);
let mut o = r.read_object()?;
o.next_key()?;
assert_eq!(o.raw()?, r#"{"line": 3}"#);
Source

pub fn unknown_field(&self) -> DecodeError

The error for the current member being one this type does not know: DecodeErrorKind::UnknownField at its key, with the key in the path. For a type that refuses unknown members.

§Examples
use jsonx_lib::{DecodeError, FromJson, Reader};

struct Strict { a: u8 }

impl<'de> FromJson<'de> for Strict {
    fn from_json(reader: &mut Reader<'de>) -> Result<Self, DecodeError> {
        let mut a = None;
        let mut o = reader.read_object()?;
        while let Some(key) = o.next_key()? {
            match &*key {
                "a" => o.field(&mut a)?,
                _ => return Err(o.unknown_field()),
            }
        }
        Ok(Strict { a: o.required(a, "a")? })
    }
}

let err = jsonx_lib::from_str::<Strict>(r#"{"a": 1, "b": 2}"#).err();
assert_eq!(err.map(|e| e.to_string()).as_deref(), Some("unknown field at byte 9 (at /b)"));
Source

pub fn required<T: FromJson<'de>>( &self, slot: Option<T>, name: &'static str, ) -> Result<T, DecodeError>

The value of a field read with field: slot’s value, or if the field was absent T’s absent value (None for an Option), or else DecodeErrorKind::MissingField at the object’s {.

§Errors

DecodeErrorKind::MissingField.

§Examples
let mut r = jsonx_lib::Reader::new("{}");
let mut o = r.read_object()?;
assert_eq!(o.next_key()?, None);
assert_eq!(o.required::<Option<u8>>(None, "maybe")?, None);
assert_eq!(o.required::<u8>(None, "must").unwrap_err().to_string(), "missing field `must` at byte 0");
Source

pub fn offset(&self) -> usize

The byte offset of the object’s {.

Auto Trait Implementations§

§

impl<'r, 'de> !UnwindSafe for ObjectReader<'r, 'de>

§

impl<'r, 'de> Forget for ObjectReader<'r, 'de>

§

impl<'r, 'de> Freeze for ObjectReader<'r, 'de>

§

impl<'r, 'de> Move for ObjectReader<'r, 'de>

§

impl<'r, 'de> RefUnwindSafe for ObjectReader<'r, 'de>

§

impl<'r, 'de> Send for ObjectReader<'r, 'de>

§

impl<'r, 'de> Sync for ObjectReader<'r, 'de>

§

impl<'r, 'de> Unpin for ObjectReader<'r, 'de>

§

impl<'r, 'de> UnsafeUnpin for ObjectReader<'r, 'de>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.