pub enum Value {
String(String),
Number(Number),
Boolean(bool),
Null,
Object(Object),
Array(Array),
}
Expand description
A value
Formatting
Formatting as JSON string
- To format as compacted JSON string, you can use
format()
orformat_as_bytes()
. - To format as a nice JSON string, you can use
format_nicely()
.
Writing as JSON string to Write
Can be done via write()
or write_nicely()
.
Converting Rust types to Value
and vice versa
There are some implementations:
impl From<...> for Value;
impl TryFrom<&Value> for ...;
impl TryFrom<Value> 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"])?.try_into_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
String(String)
Number(Number)
Boolean(bool)
Null
Object(Object)
Array(Array)
Implementations
sourceimpl Value
impl Value
sourcepub fn push<T>(&mut self, value: T) -> Result<()> where
T: Into<Self>,
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.
sourcepub fn at(&self, indexes: &[usize]) -> Result<&Self>
pub fn at(&self, indexes: &[usize]) -> Result<&Self>
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());
sourcepub fn mut_at(&mut self, indexes: &[usize]) -> Result<&mut Self>
pub fn mut_at(&mut self, indexes: &[usize]) -> Result<&mut Self>
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.
sourcepub fn take_at(&mut self, indexes: &[usize]) -> Result<Self>
pub fn take_at(&mut self, indexes: &[usize]) -> Result<Self>
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());
sourcepub fn as_array(&self) -> Result<&Array>
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.
sourcepub fn as_mut_array(&mut self) -> Result<&mut Array>
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.
sourceimpl Value
impl Value
sourcepub fn try_into_or<T>(self, default: T) -> Result<T> where
T: TryFrom<Self, Error = Error>,
pub fn try_into_or<T>(self, default: T) -> Result<T> where
T: TryFrom<Self, Error = Error>,
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 try_into_or_else()
.
Examples
let mut value = sj::parse_bytes("[null]")?;
assert!(value.take_at(&[0])?.try_into_or(true)?);
sourcepub fn try_into_or_else<T, F>(self, default: F) -> Result<T> where
T: TryFrom<Self, Error = Error>,
F: FnOnce() -> T,
pub fn try_into_or_else<T, F>(self, default: F) -> Result<T> where
T: TryFrom<Self, Error = Error>,
F: FnOnce() -> T,
Tries to convert this value into something
If this is Null
, calls default()
and returns its result.
sourcepub fn try_ref_into_or<'a, T>(&'a self, default: T) -> Result<T> where
T: TryFrom<&'a Self, Error = Error>,
pub fn try_ref_into_or<'a, T>(&'a self, default: T) -> Result<T> where
T: TryFrom<&'a Self, Error = Error>,
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 try_ref_into_or_else()
.
Examples
let value = sj::parse_bytes("[null]")?;
assert_eq!(value.at(&[0])?.try_ref_into_or(0)?, 0);
sourcepub fn try_ref_into_or_else<'a, T, F>(&'a self, default: F) -> Result<T> where
T: TryFrom<&'a Self, Error = Error>,
F: FnOnce() -> T,
pub fn try_ref_into_or_else<'a, T, F>(&'a self, default: F) -> Result<T> where
T: TryFrom<&'a Self, Error = Error>,
F: FnOnce() -> T,
Tries to convert a reference of this value into something
If this is Null
, calls default()
and returns its result.
sourceimpl Value
impl Value
sourcepub fn insert<K, V>(&mut self, key: K, value: V) -> Result<Option<Self>> where
K: Into<ObjectKey>,
V: Into<Self>,
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.
sourcepub fn by(&self, keys: &[&str]) -> Result<&Self>
pub fn by(&self, keys: &[&str]) -> Result<&Self>
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());
sourcepub fn maybe_by(&self, keys: &[&str]) -> Result<Option<&Self>>
pub fn maybe_by(&self, keys: &[&str]) -> Result<Option<&Self>>
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.
sourcepub fn mut_by(&mut self, keys: &[&str]) -> Result<&mut Self>
pub fn mut_by(&mut self, keys: &[&str]) -> Result<&mut Self>
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.
sourcepub fn maybe_mut_by(&mut self, keys: &[&str]) -> Result<Option<&mut Self>>
pub fn maybe_mut_by(&mut self, keys: &[&str]) -> Result<Option<&mut Self>>
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.
sourcepub fn take_by(&mut self, keys: &[&str]) -> Result<Self>
pub fn take_by(&mut self, keys: &[&str]) -> Result<Self>
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());
sourcepub fn maybe_take_by(&mut self, keys: &[&str]) -> Result<Option<Self>>
pub fn maybe_take_by(&mut self, keys: &[&str]) -> Result<Option<Self>>
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.
sourcepub fn as_object(&self) -> Result<&Object>
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.
sourcepub fn as_mut_object(&mut self) -> Result<&mut Object>
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.
sourceimpl Value
impl Value
sourcepub fn as_str(&self) -> Result<&str>
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.
sourcepub fn as_mut_str(&mut self) -> Result<&mut String>
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.
sourceimpl Value
impl Value
sourcepub fn format_as_bytes(&self) -> IoResult<Vec<u8>>
pub fn format_as_bytes(&self) -> IoResult<Vec<u8>>
sourcepub fn format_nicely_as_bytes(&self, tab: Option<u8>) -> IoResult<Vec<u8>>
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.
sourcepub fn format_nicely(&self, tab: Option<u8>) -> IoResult<String>
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.
sourcepub fn write<W>(&self, stream: &mut W) -> IoResult<()> where
W: Write,
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. For better performance, you should wrap your stream inside a
BufWriter
. - This function does not flush the stream when done.
sourcepub fn write_nicely<W>(&self, tab: Option<u8>, stream: &mut W) -> IoResult<()> where
W: Write,
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. For better performance, you should wrap your stream inside a
BufWriter
. - This function does not flush the stream when done.
Trait Implementations
sourceimpl FromIterator<(String, Value)> for Value
impl FromIterator<(String, Value)> for Value
sourcefn from_iter<I>(iter: I) -> Self where
I: IntoIterator<Item = (ObjectKey, Self)>,
fn from_iter<I>(iter: I) -> Self where
I: IntoIterator<Item = (ObjectKey, Self)>,
Creates a value from an iterator. Read more
sourceimpl FromIterator<Value> for Value
impl FromIterator<Value> for Value
sourcefn from_iter<T>(iter: T) -> Self where
T: IntoIterator<Item = Self>,
fn from_iter<T>(iter: T) -> Self where
T: IntoIterator<Item = Self>,
Creates a value from an iterator. Read more
Auto Trait Implementations
impl RefUnwindSafe for Value
impl Send for Value
impl Sync for Value
impl Unpin for Value
impl UnwindSafe for Value
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more