#[repr(C)]pub struct Value { /* private fields */ }
Expand description
Represents any valid JSON value.
Value
can be parsed from a JSON and from any type that implements serde::Serialize
.
§Example
use sonic_rs::json;
use sonic_rs::value::Value;
let v1 = json!({"a": 123});
let v2: Value = sonic_rs::from_str(r#"{"a": 123}"#).unwrap();
let v3 = {
use std::collections::HashMap;
let mut map: HashMap<&str, i32> = HashMap::new();
map.insert(&"a", 123);
sonic_rs::to_value(&map).unwrap()
};
assert_eq!(v1, v2);
assert_eq!(v2, v3);
assert_eq!(v1["a"], 123);
§Notes
Actually the lookup in Value
is O(n), not O(1). If you want to use Value
as a map, recommend
to use serde_json::Value
.
Implementations§
Source§impl Value
impl Value
Sourcepub fn into_object(self) -> Option<Object>
pub fn into_object(self) -> Option<Object>
Convert into Object
. If the value is not an object, return None
.
Sourcepub fn into_array(self) -> Option<Array>
pub fn into_array(self) -> Option<Array>
Convert into Array
. If the value is not an array, return None
.
Source§impl Value
impl Value
Sourcepub fn as_ref(&self) -> ValueRef<'_>
pub fn as_ref(&self) -> ValueRef<'_>
Create a reference ValueRef
from a &Value
.
§Example
use sonic_rs::{ValueRef, json, JsonValueTrait};
let v = json!({
"name": "Xiaoming",
"age": 18,
});
match v.as_ref() {
ValueRef::Object(obj) => {
assert_eq!(obj.get(&"name").unwrap().as_str().unwrap(), "Xiaoming");
assert_eq!(obj.get(&"age").unwrap().as_i64().unwrap(), 18);
},
_ => unreachable!(),
}
Sourcepub fn from_static_str(val: &'static str) -> Self
pub fn from_static_str(val: &'static str) -> Self
Create a new string Value from a &'static str
with zero-copy.
§Example
use sonic_rs::{array, JsonValueTrait, Value};
let s = "hello";
let v1 = Value::from_static_str("hello");
assert_eq!(v1.as_str().unwrap().as_ptr(), s.as_ptr());
let v2 = v1.clone();
assert_eq!(v1.as_str().unwrap().as_ptr(), v2.as_str().unwrap().as_ptr());
Sourcepub fn take(&mut self) -> Self
pub fn take(&mut self) -> Self
Take the value from the node, and set the node as a empty node. Take will creat a new root node.
§Examples
use sonic_rs::json;
use sonic_rs::JsonValueTrait;
let mut value = json!({"a": 123});
assert_eq!(value.take()["a"], 123);
assert!(value.is_null());
let mut value = json!(null);
assert!(value.take().is_null());
assert!(value.is_null());
Trait Implementations§
Source§impl Clone for Value
impl Clone for Value
Source§fn clone(&self) -> Self
fn clone(&self) -> Self
Clone the value, if the value is a root node, we will create a new allocator for it.
§Example
use sonic_rs::json;
let a = json!({"a": [1, 2, 3]});
assert_eq!(a, a.clone());
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read moreSource§impl<'de> Deserialize<'de> for Value
impl<'de> Deserialize<'de> for Value
Source§fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error>where
D: Deserializer<'de>,
fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error>where
D: Deserializer<'de>,
Deserialize this value from a Deserializer
.
§Examples
use sonic_rs::Value;
let v: Value = sonic_rs::from_str(r#"{"a": 1, "b": 2}"#).unwrap();
assert_eq!(v["a"], 1);
assert_eq!(v["b"], 2);
Source§impl<'de> Deserializer<'de> for &'de Value
impl<'de> Deserializer<'de> for &'de Value
Source§type Error = Error
type Error = Error
Source§fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserializer
to figure out how to drive the visitor based
on what data type is in the input. Read moreSource§fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting an i8
value.Source§fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting an i16
value.Source§fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting an i32
value.Source§fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting an i64
value.Source§fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a u8
value.Source§fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a u16
value.Source§fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a u32
value.Source§fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a u64
value.Source§fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a f32
value.Source§fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a f64
value.Source§fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting an optional value. Read moreSource§fn deserialize_enum<V>(
self,
_name: &str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_enum<V>(
self,
_name: &str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting an enum value with a
particular name and possible variants.Source§fn deserialize_newtype_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_newtype_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a newtype struct with a
particular name.Source§fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a bool
value.Source§fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a char
value.Source§fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a string value and does
not benefit from taking ownership of buffered data owned by the
Deserializer
. Read moreSource§fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a string value and would
benefit from taking ownership of buffered data owned by the
Deserializer
. Read moreSource§fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a byte array and does not
benefit from taking ownership of buffered data owned by the
Deserializer
. Read moreSource§fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a byte array and would
benefit from taking ownership of buffered data owned by the
Deserializer
. Read moreSource§fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a unit value.Source§fn deserialize_unit_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_unit_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a unit struct with a
particular name.Source§fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a sequence of values.Source§fn deserialize_tuple<V>(
self,
_len: usize,
visitor: V,
) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_tuple<V>(
self,
_len: usize,
visitor: V,
) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a sequence of values and
knows how many values there are without looking at the serialized data.Source§fn deserialize_tuple_struct<V>(
self,
_name: &'static str,
_len: usize,
visitor: V,
) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_tuple_struct<V>(
self,
_name: &'static str,
_len: usize,
visitor: V,
) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a tuple struct with a
particular name and number of fields.Source§fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a map of key-value pairs.Source§fn deserialize_struct<V>(
self,
_name: &'static str,
_fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_struct<V>(
self,
_name: &'static str,
_fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting a struct with a particular
name and fields.Source§fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type is expecting the name of a struct
field or the discriminant of an enum variant.Source§fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Error>where
V: Visitor<'de>,
Deserialize
type needs to deserialize a value whose type
doesn’t matter because it is ignored. Read moreSource§fn is_human_readable(&self) -> bool
fn is_human_readable(&self) -> bool
Deserialize
implementations should expect to
deserialize their human-readable form. Read moreSource§impl<'a> From<Cow<'a, str>> for Value
impl<'a> From<Cow<'a, str>> for Value
Source§fn from(value: Cow<'a, str>) -> Self
fn from(value: Cow<'a, str>) -> Self
Convert copy-on-write string to a string Value
.
§Examples
use std::borrow::Cow;
use sonic_rs::Value;
let s1: Cow<str> = Cow::Borrowed("hello");
let x1 = Value::from(s1);
let s2: Cow<str> = Cow::Owned("hello".to_string());
let x2 = Value::from(s2);
assert_eq!(x1, x2);
Source§impl<T: Into<Value>> From<Vec<T>> for Value
impl<T: Into<Value>> From<Vec<T>> for Value
Source§fn from(val: Vec<T>) -> Self
fn from(val: Vec<T>) -> Self
Convert a Vec
to a Value
.
§Examples
use sonic_rs::{json, Value};
assert_eq!(Value::from(vec!["hi", "hello"]), json!(["hi", "hello"]));
assert_eq!(Value::from(Vec::<i32>::new()), json!([]));
assert_eq!(
Value::from(vec![json!(null), json!("hi")]),
json!([null, "hi"])
);
Source§impl<'a, K: AsRef<str>, V: Clone + Into<Value>> FromIterator<(K, &'a V)> for Value
impl<'a, K: AsRef<str>, V: Clone + Into<Value>> FromIterator<(K, &'a V)> for Value
Source§fn from_iter<T: IntoIterator<Item = (K, &'a V)>>(iter: T) -> Self
fn from_iter<T: IntoIterator<Item = (K, &'a V)>>(iter: T) -> Self
Create a Value
by collecting an iterator of key-value pairs.
The key will be copied into the Value
.
§Examples
use sonic_rs::{Value, json, object};
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("sonic_rs", 40);
map.insert("json", 2);
let x: Value = map.iter().collect();
assert_eq!(x, json!({"sonic_rs": 40, "json": 2}));
let x: Value = Value::from_iter(&object!{"sonic_rs": 40, "json": 2});
assert_eq!(x, json!({"sonic_rs": 40, "json": 2}));
Source§impl<T: Into<Value>> FromIterator<T> for Value
impl<T: Into<Value>> FromIterator<T> for Value
Source§fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self
Create a Value
by collecting an iterator of array elements.
§Examples
use std::iter::FromIterator;
use sonic_rs::{json, Value};
let v = std::iter::repeat(6).take(3);
let x: Value = v.collect();
assert_eq!(x, json!([6, 6, 6]));
let x = Value::from_iter(vec!["sonic_rs", "json", "serde"]);
assert_eq!(x, json!(["sonic_rs", "json", "serde"]));
Source§impl FromStr for Value
impl FromStr for Value
Source§fn from_str(s: &str) -> Result<Self, Self::Err>
fn from_str(s: &str) -> Result<Self, Self::Err>
Convert &str
to Value
. The &str
will be copied into the Value
.
§Examples
use std::str::FromStr;
use sonic_rs::{JsonValueTrait, Value};
let x = Value::from_str("string").unwrap();
assert_eq!(x.as_str().unwrap(), "string");
§Performance
If it is &'static str
, recommend to use Value::from_static_str
.
Source§impl<I> Index<I> for Valuewhere
I: Index,
impl<I> Index<I> for Valuewhere
I: Index,
Source§fn index(&self, index: I) -> &Value
fn index(&self, index: I) -> &Value
Index into an array Value
using the syntax value[0]
and index into an
object Value
using the syntax value["k"]
.
Returns a null Value
if the Value
type does not match the index, or the
index does not exist in the array or object.
For retrieving deeply nested values, you should have a look at the Value::pointer
method.
§Examples
use sonic_rs::{json, pointer, JsonValueTrait};
let data = json!({
"x": {
"y": ["z", "zz"]
}
});
assert_eq!(data["x"]["y"], json!(["z", "zz"]));
assert_eq!(data["x"]["y"][0], json!("z"));
assert_eq!(data["a"], json!(null)); // returns null for undefined values
assert_eq!(data["a"]["b"], json!(null)); // does not panic
// use pointer for retrieving nested values
assert_eq!(data.pointer(&pointer!["x", "y", 0]).unwrap(), &json!("z"));
Source§impl<I: Index> IndexMut<I> for Value
impl<I: Index> IndexMut<I> for Value
Source§fn index_mut(&mut self, index: I) -> &mut Value
fn index_mut(&mut self, index: I) -> &mut Value
Write the index of a mutable Value
, and use the syntax value[0] = ...
in an array and value["k"] = ...
in an object.
If the index is a number, the value must be an array of length bigger than the index. Indexing into a value that is not an array or an array that is too small will panic.
If the index is a string, the value must be an object or null which is treated like an empty object. If the key is not already present in the object, it will be inserted with a value of null. Indexing into a value that is neither an object nor null will panic.
§Examples
let mut data = json!({ "x": 0, "z": null });
// replace an existing key
data["x"] = json!(1);
// insert a new key
data["y"] = json!([1, 2, 3]);
// replace an array value
data["y"][0] = json!(true);
// inserted a deeply nested key
data["a"]["b"]["c"]["d"] = json!(true);
//insert an key in a null value
data["z"]["zz"] = json!("insert in null");
data["z"]["zz1"] = object!{}.into();
assert_eq!(data, json!({
"x": 1,
"y": [true, 2, 3],
"a": { "b": {"c": {"d": true}}},
"z": {"zz": "insert in null", "zz1": {}}
}));
Source§impl<'de> IntoDeserializer<'de, Error> for &'de Value
impl<'de> IntoDeserializer<'de, Error> for &'de Value
Source§type Deserializer = &'de Value
type Deserializer = &'de Value
Source§fn into_deserializer(self) -> Self::Deserializer
fn into_deserializer(self) -> Self::Deserializer
Source§impl JsonContainerTrait for Value
impl JsonContainerTrait for Value
Source§impl JsonValueMutTrait for Value
impl JsonValueMutTrait for Value
type ValueType = Value
type ArrayType = Array
type ObjectType = Object
Source§fn as_object_mut(&mut self) -> Option<&mut Self::ObjectType>
fn as_object_mut(&mut self) -> Option<&mut Self::ObjectType>
Source§fn as_array_mut(&mut self) -> Option<&mut Self::ArrayType>
fn as_array_mut(&mut self) -> Option<&mut Self::ArrayType>
Source§fn pointer_mut<P: IntoIterator>(
&mut self,
path: P,
) -> Option<&mut Self::ValueType>
fn pointer_mut<P: IntoIterator>( &mut self, path: P, ) -> Option<&mut Self::ValueType>
Source§impl JsonValueTrait for Value
impl JsonValueTrait for Value
type ValueType<'v> = &'v Value where Self: 'v
Source§fn get_type(&self) -> JsonType
fn get_type(&self) -> JsonType
JsonType::Null
as default if self
is Option::None
or Result::Err(_)
. Read moreSource§fn as_raw_number(&self) -> Option<RawNumber>
fn as_raw_number(&self) -> Option<RawNumber>
Source§fn as_f64(&self) -> Option<f64>
fn as_f64(&self) -> Option<f64>
self
is a number, represent it as f64 if possible. Returns None otherwise.
The integer number will be converted to f64. Read moreSource§fn pointer<P: IntoIterator>(&self, path: P) -> Option<Self::ValueType<'_>>
fn pointer<P: IntoIterator>(&self, path: P) -> Option<Self::ValueType<'_>>
Source§fn get<I: Index>(&self, index: I) -> Option<Self::ValueType<'_>>
fn get<I: Index>(&self, index: I) -> Option<Self::ValueType<'_>>
Source§fn is_boolean(&self) -> bool
fn is_boolean(&self) -> bool
bool
. Read moreSource§fn is_f64(&self) -> bool
fn is_f64(&self) -> bool
f64
.
It will returns false if the value is a u64
or i64
. Read moreSource§impl<'de> TryFrom<LazyValue<'de>> for Value
impl<'de> TryFrom<LazyValue<'de>> for Value
Try parse a LazyValue
into a Value
. LazyValue
is always a valid JSON, at least it is
followed the JSON syntax.
However, in some cases, the parse will failed and return errors, such as the float number in JSON is inifity.
Source§impl TryFrom<f32> for Value
impl TryFrom<f32> for Value
Source§fn try_from(value: f32) -> Result<Self, Self::Error>
fn try_from(value: f32) -> Result<Self, Self::Error>
Try convert a f32 to Value
. If the float is NaN or infinity, return a error.
§Examples
use sonic_rs::{JsonValueTrait, Value};
let f1: f32 = 2.333;
let x1: Value = f1.try_into().unwrap();
assert_eq!(x1, f1);
let x2: Value = f32::INFINITY.try_into().unwrap_or_default();
let x3: Value = f32::NAN.try_into().unwrap_or_default();
assert!(x2.is_null() && x3.is_null());
Source§impl TryFrom<f64> for Value
impl TryFrom<f64> for Value
Source§type Error = Error
type Error = Error
Try convert a f64 to Value
. If the float is NaN or infinity, return a error.
§Examples
use sonic_rs::{JsonValueTrait, Value};
let f1: f64 = 2.333;
let x1: Value = f1.try_into().unwrap();
assert_eq!(x1, 2.333);
let x2: Value = f64::INFINITY.try_into().unwrap_or_default();
let x3: Value = f64::NAN.try_into().unwrap_or_default();
assert!(x2.is_null() && x3.is_null());
impl Eq for Value
impl Send for Value
impl Sync for Value
Auto Trait Implementations§
impl Freeze for Value
impl !RefUnwindSafe for Value
impl Unpin for Value
impl !UnwindSafe for Value
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§unsafe fn clone_to_uninit(&self, dst: *mut T)
unsafe fn clone_to_uninit(&self, dst: *mut T)
clone_to_uninit
)