Enum sj::Json

source ·
pub enum Json {
    String(String),
    Number(Number),
    Boolean(bool),
    Null,
    Object(Object),
    Array(Array),
}
Expand description

Json

Formatting

Formatting as JSON string

  • To format as compacted JSON string, you can use format() or format_as_bytes().
  • To format as a nice JSON string, you can use format_nicely().
  • Currently the order of keys in input objects will not be preserved. See Object for more details.

Writing as JSON string to Write

Can be done via write() or write_nicely().

Converting Rust types to Json and vice versa

There are some implementations:

impl From<...> for Json;
impl TryFrom<&Json> for ...;
impl TryFrom<Json> for ...;

About TryFrom implementations:

  • For primitives, since they’re cheap, they have implementations on either a borrowed or an owned value.
  • For collections such as String, Object, Array…, they only have implementations on an owned value. So data is moved, not copied.

Shortcuts

A root JSON value can be either an object or an array. For your convenience, there are some shortcuts, like below examples.

  • Object:

    
    let mut object = sj::object();
    object.insert("first", true)?;
    object.insert("second", <Option<u8>>::None)?;
    object.insert(String::from("third"), "...")?;
    
    assert!(bool::try_from(object.by("first")?)?);
    assert!(object.take_by("second")?.map_or(true)?);
    assert!(
        [r#"{"first":true,"third":"..."}"#, r#"{"third":"...","first":true}"#]
            .contains(&object.format()?.as_str())
    );
  • Array:

    
    let mut array = sj::array();
    array.push(false)?;
    array.push("a string")?;
    array.push(Some(sj::object()))?;
    
    assert!(bool::try_from(array.at(0)?)? == false);
    assert_eq!(array.format()?, r#"[false,"a string",{}]"#);

Variants§

Implementations§

source§

impl Json

source

pub fn push<T>(&mut self, value: T) -> Result<()>where T: Into<Self>,

If the value is an array, pushes new item into it

Returns an error if the value is not an array.

source

pub fn at<'a, I, const N: usize>(&self, indexes: I) -> Result<&Self>where I: Into<ArrayIndexes<'a, N>>,

Gets an immutable item from this array and its sub arrays

The function returns an error on one of these conditions:

  • Indexes are empty or invalid.
  • The value or any of its sub items is not an array.
Examples
let mut array = sj::array();
array.push("first")?;
array.push(vec![false.into(), "second".into()])?;

assert_eq!(array.at(0)?.as_str()?, "first");
assert_eq!(array.at([1, 1])?.as_str()?, "second");

assert!(array.at(&[][..]).is_err());
assert!(array.at([0, 1]).is_err());
assert!(array.at([1, 2]).is_err());
assert!(array.at([1, 0, 0]).is_err());
assert!(array.at([1, 1, 2]).is_err());
source

pub fn mut_at<'a, I, const N: usize>(&mut self, indexes: I) -> Result<&mut Self>where I: Into<ArrayIndexes<'a, N>>,

Gets a mutable item from this array and its sub arrays

The function returns an error on one of these conditions:

  • Indexes are empty or invalid.
  • The value or any of its sub items is not an array.
source

pub fn take_at<'a, I, const N: usize>(&mut self, indexes: I) -> Result<Self>where I: Into<ArrayIndexes<'a, N>>,

Takes an item from this array and its sub arrays

The function returns an error on one of these conditions:

  • Indexes are empty or invalid.
  • The value or any of its sub items is not an array.
Examples
let mut array = sj::array();
array.push("earth")?;
array.push(vec![false.into(), "moon".into()])?;

assert_eq!(array.take_at(0)?.as_str()?, "earth");
assert_eq!(array.take_at([0, 1])?.as_str()?, "moon");

assert!(array.take_at(&[][..]).is_err());
assert!(array.take_at([0, 1]).is_err());
source

pub fn as_array(&self) -> Result<&Array>

If the value is an array, returns an immutable reference of it

Returns an error if the value is not an array.

source

pub fn as_mut_array(&mut self) -> Result<&mut Array>

If the value is an array, returns a mutable reference of it

Returns an error if the value is not an array.

source§

impl Json

source

pub fn is_null(&self) -> bool

source

pub fn map<T, E>(self) -> Result<Option<T>, E>where T: TryFrom<Self, Error = E>,

Maps this value into something

If this is Null, returns None.

source

pub fn map_ref<'a, T, E>(&'a self) -> Result<Option<T>, E>where T: TryFrom<&'a Self, Error = E>,

Maps this value into something

If this is Null, returns None.

source

pub fn map_or<T, E>(self, default: T) -> Result<T, E>where T: TryFrom<Self, Error = E>,

Tries to convert this value into something

If this is Null, returns default.

If your default value would be a result of a function call, you should use map_or_else().

Examples
let mut value = sj::parse_bytes("[null]")?;
assert!(value.take_at(0)?.map_or(true)?);
source

pub fn map_or_else<T, E, F>(self, default: F) -> Result<T, E>where T: TryFrom<Self, Error = E>, F: FnOnce() -> T,

Tries to convert this value into something

If this is Null, calls default() and returns its result.

source

pub fn map_ref_or<'a, T, E>(&'a self, default: T) -> Result<T, E>where T: TryFrom<&'a Self, Error = E>,

Tries to convert a reference of this value into something

If this is Null, returns default.

If your default value would be a result of a function call, you should use map_ref_or_else().

Examples
let value = sj::parse_bytes("[null]")?;
assert_eq!(value.at(0)?.map_ref_or(0)?, 0);
source

pub fn map_ref_or_else<'a, T, E, F>(&'a self, default: F) -> Result<T, E>where T: TryFrom<&'a Self, Error = E>, F: FnOnce() -> T,

Tries to convert a reference of this value into something

If this is Null, calls default() and returns its result.

source§

impl Json

source

pub fn insert<K, V>(&mut self, key: K, value: V) -> Result<Option<Self>>where K: Into<ObjectKey>, V: Into<Self>,

If the value is an object, inserts new item into it

On success, returns previous value (if it existed).

Returns an error if the value is not an object.

source

pub fn by<'a, K, const N: usize>(&self, keys: K) -> Result<&Self>where K: Into<ObjectIndexes<'a, N>>,

Gets an immutable item from this object and its sub objects

The function returns an error on one of these conditions:

  • Keys are empty.
  • The value or any of its sub items is not an object.
Examples
let mut object = sj::object();
object.insert("first", true)?;
object.insert("second", {
    let mut map = sj::Object::new();
    sj::insert(&mut map, "zero", 0);
    map
})?;

assert_eq!(bool::try_from(object.by("first")?)?, true);
assert_eq!(u8::try_from(object.by(["second", "zero"])?)?, 0);

assert!(object.by("something").is_err());
assert!(object.maybe_by("something")?.is_none());

assert!(object.by(&[][..]).is_err());
assert!(object.by(["first", "last"]).is_err());
assert!(object.by(["second", "third", "fourth"]).is_err());
source

pub fn maybe_by<'a, K, const N: usize>(&self, keys: K) -> Result<Option<&Self>>where K: Into<ObjectIndexes<'a, N>>,

Gets an optional immutable item from this object and its sub objects

The function returns an error on one of these conditions:

  • Keys are empty.
  • The value or any of its sub items is not an object.
source

pub fn mut_by<'a, K, const N: usize>(&mut self, keys: K) -> Result<&mut Self>where K: Into<ObjectIndexes<'a, N>>,

Gets a mutable item from this object and its sub objects

The function returns an error on one of these conditions:

  • Keys are empty.
  • The value or any of its sub items is not an object.
source

pub fn maybe_mut_by<'a, K, const N: usize>( &mut self, keys: K ) -> Result<Option<&mut Self>>where K: Into<ObjectIndexes<'a, N>>,

Gets an optional mutable item from this object and its sub objects

The function returns an error on one of these conditions:

  • Keys are empty.
  • The value or any of its sub items is not an object.
source

pub fn take_by<'a, K, const N: usize>(&mut self, keys: K) -> Result<Self>where K: Into<ObjectIndexes<'a, N>>,

Takes an item from this object and its sub objects

The function returns an error on one of these conditions:

  • Keys are empty.
  • The value or any of its sub items is not an object.
Examples
let mut object = sj::object();
object.insert("earth", "moon")?;
object.insert("solar-system", {
    let mut map = sj::Object::new();
    sj::insert(&mut map, "sun", "earth");
    map
})?;

assert_eq!(object.take_by("earth")?.as_str()?, "moon");
assert_eq!(object.take_by(["solar-system", "sun"])?.as_str()?, "earth");

assert!(object.take_by("milky-way").is_err());
assert!(object.maybe_take_by("milky-way")?.is_none());
assert!(object.maybe_take_by(["solar-system", "mars"])?.is_none());

assert!(object.take_by(&[][..]).is_err());
assert!(object.take_by(["jupiter", "venus"]).is_err());
source

pub fn maybe_take_by<'a, K, const N: usize>( &mut self, keys: K ) -> Result<Option<Self>>where K: Into<ObjectIndexes<'a, N>>,

Takes an optional item from this object and its sub objects

The function returns an error on one of these conditions:

  • Keys are empty.
  • The value or any of its sub items is not an object.
source

pub fn as_object(&self) -> Result<&Object>

If the value is an object, returns an immutable reference of it

Returns an error if the value is not an object.

source

pub fn as_mut_object(&mut self) -> Result<&mut Object>

If the value is an object, returns a mutable reference of it

Returns an error if the value is not an object.

source§

impl Json

source

pub fn as_str(&self) -> Result<&str>

If the value is a string, returns an immutable reference of it

Returns an error if the value is not a string.

source

pub fn as_mut_str(&mut self) -> Result<&mut String>

If the value is a string, returns a mutable reference of it

Returns an error if the value is not a string.

source§

impl Json

source

pub fn format_as_bytes(&self) -> IoResult<Vec<u8>>

source

pub fn format_nicely_as_bytes(&self, tab: Option<u8>) -> IoResult<Vec<u8>>

Nicely formats this value as JSON string

If you don’t provide tab size, default (4) will be used.

source

pub fn format(&self) -> IoResult<String>

source

pub fn format_nicely(&self, tab: Option<u8>) -> IoResult<String>

Nicely formats this value as JSON string

If you don’t provide tab size, default (4) will be used.

source

pub fn write<W>(&self, stream: &mut W) -> IoResult<()>where W: Write,

Writes this value as compacted JSON string to a stream
Notes
  • The stream is used as-is. You might want to consider using BufWriter.
  • This function does not flush the stream when done.
source

pub fn write_nicely<W>(&self, tab: Option<u8>, stream: &mut W) -> IoResult<()>where W: Write,

Writes this value as nicely formatted JSON string to a stream
Notes
  • If you don’t provide tab size, default (4) will be used.
  • The stream is used as-is. You might want to consider using BufWriter.
  • This function does not flush the stream when done.

Trait Implementations§

source§

impl Clone for Json

source§

fn clone(&self) -> Json

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Json

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for Json

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl From<&str> for Json

source§

fn from(s: &str) -> Self

Converts to this type from the input type.
source§

impl<K, V, const N: usize> From<[(K, V); N]> for Jsonwhere K: Into<ObjectKey>, V: Into<Self>,

source§

fn from(array: [(K, V); N]) -> Self

Converts to this type from the input type.
source§

impl From<()> for Json

source§

fn from(_: ()) -> Self

Converts to this type from the input type.
source§

impl<K, V> From<(K, V)> for Jsonwhere K: Into<ObjectKey>, V: Into<Self>,

source§

fn from((key, value): (K, V)) -> Self

Converts to this type from the input type.
source§

impl From<BTreeMap<String, Json, Global>> for Json

source§

fn from(map: Object) -> Self

Converts to this type from the input type.
source§

impl From<Cow<'_, str>> for Json

source§

fn from(s: Cow<'_, str>) -> Self

Converts to this type from the input type.
source§

impl From<Number> for Json

source§

fn from(n: Number) -> Self

Converts to this type from the input type.
source§

impl<T> From<Option<T>> for Jsonwhere T: Into<Json>,

source§

fn from(t: Option<T>) -> Self

Converts to this type from the input type.
source§

impl From<String> for Json

source§

fn from(s: String) -> Self

Converts to this type from the input type.
source§

impl From<Vec<Json, Global>> for Json

source§

fn from(values: Array) -> Self

Converts to this type from the input type.
source§

impl From<bool> for Json

source§

fn from(b: bool) -> Self

Converts to this type from the input type.
source§

impl From<f32> for Json

source§

fn from(n: f32) -> Self

Converts to this type from the input type.
source§

impl From<f64> for Json

source§

fn from(n: f64) -> Self

Converts to this type from the input type.
source§

impl From<i128> for Json

source§

fn from(n: i128) -> Self

Converts to this type from the input type.
source§

impl From<i16> for Json

source§

fn from(n: i16) -> Self

Converts to this type from the input type.
source§

impl From<i32> for Json

source§

fn from(n: i32) -> Self

Converts to this type from the input type.
source§

impl From<i64> for Json

source§

fn from(n: i64) -> Self

Converts to this type from the input type.
source§

impl From<i8> for Json

source§

fn from(n: i8) -> Self

Converts to this type from the input type.
source§

impl From<isize> for Json

source§

fn from(n: isize) -> Self

Converts to this type from the input type.
source§

impl From<u128> for Json

source§

fn from(n: u128) -> Self

Converts to this type from the input type.
source§

impl From<u16> for Json

source§

fn from(n: u16) -> Self

Converts to this type from the input type.
source§

impl From<u32> for Json

source§

fn from(n: u32) -> Self

Converts to this type from the input type.
source§

impl From<u64> for Json

source§

fn from(n: u64) -> Self

Converts to this type from the input type.
source§

impl From<u8> for Json

source§

fn from(n: u8) -> Self

Converts to this type from the input type.
source§

impl From<usize> for Json

source§

fn from(n: usize) -> Self

Converts to this type from the input type.
source§

impl<K, V> FromIterator<(K, V)> for Jsonwhere K: Into<ObjectKey>, V: Into<Self>,

source§

fn from_iter<I>(iter: I) -> Selfwhere I: IntoIterator<Item = (K, V)>,

Creates a value from an iterator. Read more
source§

impl FromIterator<Json> for Json

source§

fn from_iter<T>(iter: T) -> Selfwhere T: IntoIterator<Item = Self>,

Creates a value from an iterator. Read more
source§

impl FromStr for Json

§

type Err = Error

The associated error which can be returned from parsing.
source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
source§

impl TryFrom<&Json> for bool

§

type Error = Error

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

fn try_from(value: &Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<&Json> for f32

§

type Error = Error

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

fn try_from(value: &Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<&Json> for f64

§

type Error = Error

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

fn try_from(value: &Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<&Json> for i128

§

type Error = Error

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

fn try_from(value: &Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<&Json> for i16

§

type Error = Error

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

fn try_from(value: &Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<&Json> for i32

§

type Error = Error

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

fn try_from(value: &Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<&Json> for i64

§

type Error = Error

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

fn try_from(value: &Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<&Json> for i8

§

type Error = Error

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

fn try_from(value: &Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<&Json> for isize

§

type Error = Error

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

fn try_from(value: &Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<&Json> for u128

§

type Error = Error

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

fn try_from(value: &Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<&Json> for u16

§

type Error = Error

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

fn try_from(value: &Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<&Json> for u32

§

type Error = Error

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

fn try_from(value: &Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<&Json> for u64

§

type Error = Error

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

fn try_from(value: &Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<&Json> for u8

§

type Error = Error

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

fn try_from(value: &Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<&Json> for usize

§

type Error = Error

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

fn try_from(value: &Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Json> for Array

§

type Error = Error

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

fn try_from(value: Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Json> for Object

§

type Error = Error

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

fn try_from(value: Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Json> for String

§

type Error = Error

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

fn try_from(value: Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Json> for bool

§

type Error = Error

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

fn try_from(value: Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Json> for f32

§

type Error = Error

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

fn try_from(value: Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Json> for f64

§

type Error = Error

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

fn try_from(value: Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Json> for i128

§

type Error = Error

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

fn try_from(value: Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Json> for i16

§

type Error = Error

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

fn try_from(value: Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Json> for i32

§

type Error = Error

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

fn try_from(value: Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Json> for i64

§

type Error = Error

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

fn try_from(value: Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Json> for i8

§

type Error = Error

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

fn try_from(value: Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Json> for isize

§

type Error = Error

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

fn try_from(value: Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Json> for u128

§

type Error = Error

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

fn try_from(value: Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Json> for u16

§

type Error = Error

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

fn try_from(value: Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Json> for u32

§

type Error = Error

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

fn try_from(value: Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Json> for u64

§

type Error = Error

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

fn try_from(value: Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Json> for u8

§

type Error = Error

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

fn try_from(value: Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Json> for usize

§

type Error = Error

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

fn try_from(value: Json) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Vec<u8, Global>> for Json

§

type Error = Error

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

fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error>

Performs the conversion.

Auto Trait Implementations§

§

impl RefUnwindSafe for Json

§

impl Send for Json

§

impl Sync for Json

§

impl Unpin for Json

§

impl UnwindSafe for Json

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

const: unstable · source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

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

const: unstable · 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> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

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

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

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

§

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

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.