JsonValue

Enum JsonValue 

Source
pub enum JsonValue {
    Number(f64),
    Boolean(bool),
    String(String),
    Null,
    Array(Vec<JsonValue>),
    Object(HashMap<String, JsonValue>),
}
Expand description

Enum to represent one JSON value. Each variant represents corresponding JSON types.

use tinyjson::JsonValue;
use std::convert::TryInto;

// Convert from raw values using `From` trait
let value = JsonValue::from("this is string".to_string());

// Get reference to inner value
let maybe_number: Option<&f64> = value.get();
assert!(maybe_number.is_none());
let maybe_string: Option<&String> = value.get();
assert!(maybe_string.is_some());

// Check type of JSON value
assert!(matches!(value, JsonValue::String(_)));
assert!(value.is_string());

// Convert into raw values using `TryInto` trait
let original_value: String = value.try_into().unwrap();

Variants§

§

Number(f64)

Number type value.

§

Boolean(bool)

Boolean type value.

§

String(String)

String type value.

§

Null

Null type value.

§

Array(Vec<JsonValue>)

Array type value.

§

Object(HashMap<String, JsonValue>)

Object type value.

Implementations§

Source§

impl JsonValue

Source

pub fn get<T: InnerAsRef>(&self) -> Option<&T>

Get immutable reference to the inner value.

use tinyjson::JsonValue;

let value: JsonValue = "[1, 2, 3]".parse().unwrap();
let vec: &Vec<_> = value.get().unwrap();
assert_eq!(vec[0], JsonValue::from(1.0));

// Try to convert with incorrect type
assert!(value.get::<f64>().is_none());
Source

pub fn get_mut<T: InnerAsRefMut>(&mut self) -> Option<&mut T>

Get mutable reference to the inner value.

use tinyjson::JsonValue;

let mut value: JsonValue = "[1, 2, 3]".parse().unwrap();
let vec: &mut Vec<_> = value.get_mut().unwrap();
vec[0] = JsonValue::from(false);
assert_eq!(value.stringify().unwrap(), "[false,2,3]");

// Try to convert with incorrect type
assert!(value.get_mut::<f64>().is_none());
Source

pub fn is_bool(&self) -> bool

Check if the inner value is a boolean.

use tinyjson::JsonValue;

let v = JsonValue::from(true);
assert!(v.is_bool());
let v = JsonValue::from(1.0);
assert!(!v.is_bool());
Source

pub fn is_number(&self) -> bool

Check if the inner value is a number.

use tinyjson::JsonValue;

let v = JsonValue::from(1.0);
assert!(v.is_number());
let v = JsonValue::from(false);
assert!(!v.is_number());
Source

pub fn is_string(&self) -> bool

Check if the inner value is a string.

use tinyjson::JsonValue;

let v = JsonValue::from("foo".to_string());
assert!(v.is_string());
let v = JsonValue::from(1.0);
assert!(!v.is_string());
Source

pub fn is_null(&self) -> bool

Check if the inner value is null.

use tinyjson::JsonValue;

let v = JsonValue::from(()); // () is inner representation of null value
assert!(v.is_null());
let v = JsonValue::from(false);
assert!(!v.is_null());
Source

pub fn is_array(&self) -> bool

Check if the inner value is an array.

use tinyjson::JsonValue;

let v = JsonValue::from(vec![]);
assert!(v.is_array());
let v = JsonValue::from(1.0);
assert!(!v.is_array());
Source

pub fn is_object(&self) -> bool

Check if the inner value is an object.

use tinyjson::JsonValue;
use std::collections::HashMap;

let v = JsonValue::from(HashMap::new());
assert!(v.is_object());
let v = JsonValue::from(vec![]);
assert!(!v.is_object());
Source

pub fn stringify(&self) -> JsonGenerateResult

Convert this JSON value to String value.

use tinyjson::JsonValue;

let v = JsonValue::from(vec![1.0.into(), true.into(), "str".to_string().into()]);
let s = v.stringify().unwrap();
assert_eq!(&s, "[1,true,\"str\"]");
Source

pub fn write_to<W: Write>(&self, w: &mut W) -> Result<()>

Write this JSON value to the given io::Write object as UTF-8 byte sequence.

use tinyjson::JsonValue;
use std::io::Write;

let v = JsonValue::from(vec![1.0.into(), true.into(), "str".to_string().into()]);
let mut bytes = vec![];
v.write_to(&mut bytes).unwrap();
assert_eq!(&String::from_utf8(bytes).unwrap(), "[1,true,\"str\"]");
Source

pub fn format(&self) -> JsonGenerateResult

Convert this JSON value to String value with 2-spaces indentation.

use tinyjson::JsonValue;

let v = JsonValue::from(vec![1.0.into(), true.into(), "str".to_string().into()]);
let s = v.format().unwrap();
assert_eq!(&s,
"[
  1,
  true,
  \"str\"
]");
Source

pub fn format_to<W: Write>(&self, w: &mut W) -> Result<()>

Write this JSON value to the given io::Write object as UTF-8 byte sequence with 2-spaces indentation.

use tinyjson::JsonValue;

let v = JsonValue::from(vec![1.0.into(), true.into(), "str".to_string().into()]);
let mut bytes = vec![];
v.format_to(&mut bytes).unwrap();
assert_eq!(&String::from_utf8(bytes).unwrap(),
"[
  1,
  true,
  \"str\"
]");

Trait Implementations§

Source§

impl Clone for JsonValue

Source§

fn clone(&self) -> JsonValue

Returns a duplicate 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 JsonValue

Source§

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

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

impl From<()> for JsonValue

Convert () into JsonValue. () is an inner representation of null JSON value.

use tinyjson::JsonValue;
let v = JsonValue::from(());
assert!(v.is_null());
Source§

fn from(_x: ()) -> JsonValue

Converts to this type from the input type.
Source§

impl From<HashMap<String, JsonValue>> for JsonValue

Convert HashMap value into JsonValue.

use tinyjson::JsonValue;
use std::collections::HashMap;
let mut m = HashMap::new();
m.insert("foo".to_string(), 1.0.into());
let v = JsonValue::from(m);
assert!(v.is_object());
Source§

fn from(o: HashMap<String, JsonValue>) -> JsonValue

Converts to this type from the input type.
Source§

impl From<String> for JsonValue

Convert bool value into JsonValue. Note that &str is not available. Explicitly allocate String object and pass it.

use tinyjson::JsonValue;
let v = JsonValue::from("foo".to_string());
assert!(v.is_string());
Source§

fn from(s: String) -> JsonValue

Converts to this type from the input type.
Source§

impl From<UnexpectedValue> for JsonValue

Convert this error into the value which failed to be converted.

use tinyjson::JsonValue;
use std::convert::TryFrom;

let error = String::try_from(JsonValue::from(1.0)).unwrap_err();
assert_eq!(JsonValue::from(error), JsonValue::Number(1.0));
Source§

fn from(err: UnexpectedValue) -> Self

Converts to this type from the input type.
Source§

impl From<Vec<JsonValue>> for JsonValue

Convert Vec value into JsonValue.

use tinyjson::JsonValue;
let v = JsonValue::from(vec![1.0.into(), true.into()]);
assert!(v.is_array());
Source§

fn from(a: Vec<JsonValue>) -> JsonValue

Converts to this type from the input type.
Source§

impl From<bool> for JsonValue

Convert bool value into JsonValue.

use tinyjson::JsonValue;
let v = JsonValue::from(true);
assert!(v.is_bool());
Source§

fn from(b: bool) -> JsonValue

Converts to this type from the input type.
Source§

impl From<f64> for JsonValue

Convert f64 value into JsonValue.

use tinyjson::JsonValue;
let v = JsonValue::from(1.0);
assert!(v.is_number());
Source§

fn from(n: f64) -> JsonValue

Converts to this type from the input type.
Source§

impl FromStr for JsonValue

Parse given str object into JsonValue value. This is recommended way to parse strings into JSON value with this library.

use tinyjson::JsonValue;

let array: JsonValue = "[1, 2, 3]".parse().unwrap();
assert!(array.is_array());
Source§

type Err = JsonParseError

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<'a> Index<&'a str> for JsonValue

Access to value of the key of object.

use tinyjson::JsonValue;
use std::collections::HashMap;

let mut m = HashMap::new();
m.insert("foo".to_string(), 1.0.into());
let v = JsonValue::from(m);
let i = &v["foo"];
assert_eq!(i, &JsonValue::Number(1.0));

This will panic when the given JsonValue value is not an object

let v = JsonValue::from(vec![]);
let _ = &v["foo"]; // Panic

or when the key does not exist in the object.

let v = JsonValue::from(HashMap::new());
let _ = &v["foo"]; // Panic

Using this operator, you can access the nested elements quickly

let mut json: JsonValue = r#"
{
  "foo": {
    "bar": [
      { "target": 42 }
    ]
  }
}
"#.parse().unwrap();

// Access with index operator
let target_value: f64 = *json["foo"]["bar"][0]["target"].get().unwrap();
assert_eq!(target_value, 42.0);
Source§

type Output = JsonValue

The returned type after indexing.
Source§

fn index(&self, key: &'a str) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl Index<usize> for JsonValue

Access to value of the index of array.

use tinyjson::JsonValue;

let v = JsonValue::from(vec![1.0.into(), true.into()]);
let b = &v[1];
assert_eq!(b, &JsonValue::Boolean(true));

This will panic when the given JsonValue value is not an array

use std::collections::HashMap;
let v = JsonValue::from(HashMap::new());
let _ = &v[0]; // Panic

or when the index is out of bounds.

let v = JsonValue::from(vec![]);
let _ = &v[0]; // Panic
Source§

type Output = JsonValue

The returned type after indexing.
Source§

fn index(&self, index: usize) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl<'a> IndexMut<&'a str> for JsonValue

Access to value of the key of mutable object.

use tinyjson::JsonValue;
use std::collections::HashMap;

let mut m = HashMap::new();
m.insert("foo".to_string(), 1.0.into());
let mut v = JsonValue::from(m);
v["foo"] = JsonValue::Number(3.14);
assert_eq!(v["foo"], JsonValue::Number(3.14));

This will panic when the given JsonValue value is not an object

let mut v = JsonValue::from(vec![]);
let _ = &mut v["foo"]; // Panic

or when the key does not exist in the object.

let mut v = JsonValue::from(HashMap::new());
let _ = &mut v["foo"]; // Panic

Using this operator, you can modify the nested elements quickly

let mut json: JsonValue = r#"
{
  "foo": {
    "bar": [
      { "target": 42 }
    ]
  }
}
"#.parse().unwrap();

// Modify with index operator
json["foo"]["bar"][0]["target"] = JsonValue::Boolean(false);
assert_eq!(json["foo"]["bar"][0]["target"], JsonValue::Boolean(false));
Source§

fn index_mut(&mut self, key: &'a str) -> &mut Self::Output

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl IndexMut<usize> for JsonValue

Access to value of the index of mutable array.

use tinyjson::JsonValue;

let mut v = JsonValue::from(vec![1.0.into(), true.into()]);
let b = &mut v[1];
assert_eq!(b, &JsonValue::Boolean(true));

This will panic when the given JsonValue value is not an array

use std::collections::HashMap;
let mut v = JsonValue::from(HashMap::new());
let _ = &mut v[0]; // Panic

or when the index is out of bounds.

let mut v = JsonValue::from(vec![]);
let _ = &mut v[0]; // Panic
Source§

fn index_mut(&mut self, index: usize) -> &mut Self::Output

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl PartialEq for JsonValue

Source§

fn eq(&self, other: &JsonValue) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl TryFrom<JsonValue> for ()

Try to convert the JsonValue value into (). Note that () is an inner representation of null JSON value. UnexpectedValue error happens when trying to convert an incorrect type value.

use tinyjson::JsonValue;
use std::convert::TryFrom;

let v = JsonValue::from(());
let r = <()>::try_from(v);
assert!(r.is_ok());

let v = JsonValue::from(1.0);
let r = <()>::try_from(v);
assert!(r.is_err());
Source§

type Error = UnexpectedValue

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

fn try_from(v: JsonValue) -> Result<Self, UnexpectedValue>

Performs the conversion.
Source§

impl TryFrom<JsonValue> for HashMap<String, JsonValue>

Try to convert the JsonValue value into HashMap<String, JsonValue>. UnexpectedValue error happens when trying to convert an incorrect type value.

use tinyjson::JsonValue;
use std::convert::TryFrom;
use std::collections::HashMap;

let mut m = HashMap::new();
m.insert("foo".to_string(), 42.0.into());
let v = JsonValue::from(m);
let r = <HashMap<_, _>>::try_from(v);
assert!(r.is_ok());

let v = JsonValue::from(1.0);
let r = <HashMap<_, _>>::try_from(v);
assert!(r.is_err());
Source§

type Error = UnexpectedValue

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

fn try_from(v: JsonValue) -> Result<Self, UnexpectedValue>

Performs the conversion.
Source§

impl TryFrom<JsonValue> for String

Try to convert the JsonValue value into String. UnexpectedValue error happens when trying to convert an incorrect type value.

use tinyjson::JsonValue;
use std::convert::TryFrom;

let v = JsonValue::from("foo".to_string());
let r = String::try_from(v);
assert!(r.is_ok());

let v = JsonValue::from(1.0);
let r = String::try_from(v);
assert!(r.is_err());
Source§

type Error = UnexpectedValue

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

fn try_from(v: JsonValue) -> Result<Self, UnexpectedValue>

Performs the conversion.
Source§

impl TryFrom<JsonValue> for Vec<JsonValue>

Try to convert the JsonValue value into Vec<JsonValue>. UnexpectedValue error happens when trying to convert an incorrect type value.

use tinyjson::JsonValue;
use std::convert::TryFrom;

let v = JsonValue::from(vec![true.into()]);
let r = <Vec<_>>::try_from(v);
assert!(r.is_ok());

let v = JsonValue::from(1.0);
let r = <Vec<_>>::try_from(v);
assert!(r.is_err());
Source§

type Error = UnexpectedValue

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

fn try_from(v: JsonValue) -> Result<Self, UnexpectedValue>

Performs the conversion.
Source§

impl TryFrom<JsonValue> for bool

Try to convert the JsonValue value into bool. UnexpectedValue error happens when trying to convert an incorrect type value.

use tinyjson::JsonValue;
use std::convert::TryFrom;

let v = JsonValue::from(true);
let r = bool::try_from(v);
assert!(r.is_ok());

let v = JsonValue::from(1.0);
let r = bool::try_from(v);
assert!(r.is_err());
Source§

type Error = UnexpectedValue

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

fn try_from(v: JsonValue) -> Result<Self, UnexpectedValue>

Performs the conversion.
Source§

impl TryFrom<JsonValue> for f64

Try to convert the JsonValue value into f64. UnexpectedValue error happens when trying to convert an incorrect type value.

use tinyjson::JsonValue;
use std::convert::TryFrom;

let v = JsonValue::from(1.0);
let r = f64::try_from(v);
assert!(r.is_ok());

let v = JsonValue::from(true);
let r = f64::try_from(v);
assert!(r.is_err());
Source§

type Error = UnexpectedValue

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

fn try_from(v: JsonValue) -> Result<Self, UnexpectedValue>

Performs the conversion.
Source§

impl StructuralPartialEq for JsonValue

Auto Trait Implementations§

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

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 T
where U: Into<T>,

Source§

type Error = Infallible

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

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

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.