Enum tinyjson::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§

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());

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());

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());

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());

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());

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());

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());

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());

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\"]");

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\"]");

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\"
]");

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§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more

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

use tinyjson::JsonValue;
let v = JsonValue::from(());
assert!(v.is_null());
Converts to this type from the input type.

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());
Converts to this type from the input type.

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());
Converts to this type from the input type.

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));
Converts to this type from the input type.

Convert Vec value into JsonValue.

use tinyjson::JsonValue;
let v = JsonValue::from(vec![1.0.into(), true.into()]);
assert!(v.is_array());
Converts to this type from the input type.

Convert bool value into JsonValue.

use tinyjson::JsonValue;
let v = JsonValue::from(true);
assert!(v.is_bool());
Converts to this type from the input type.

Convert f64 value into JsonValue.

use tinyjson::JsonValue;
let v = JsonValue::from(1.0);
assert!(v.is_number());
Converts to this type from the input type.

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());
The associated error which can be returned from parsing.
Parses a string s to return a value of this type. Read more

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);
The returned type after indexing.
Performs the indexing (container[index]) operation. Read more

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
The returned type after indexing.
Performs the indexing (container[index]) operation. Read more

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));
Performs the mutable indexing (container[index]) operation. Read more

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
Performs the mutable indexing (container[index]) operation. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

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());
The type returned in the event of a conversion error.
Performs the conversion.

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());
The type returned in the event of a conversion error.
Performs the conversion.

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());
The type returned in the event of a conversion error.
Performs the conversion.

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());
The type returned in the event of a conversion error.
Performs the conversion.

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());
The type returned in the event of a conversion error.
Performs the conversion.

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());
The type returned in the event of a conversion error.
Performs the conversion.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

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

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.