Module serde_json::value [−][src]
The Value enum, a loosely typed way of representing any valid JSON value.
Constructing JSON
Serde JSON provides a json!
macro to build serde_json::Value
objects with very natural JSON syntax. In order to use this macro,
serde_json
needs to be imported with the #[macro_use]
attribute.
#[macro_use] extern crate serde_json; fn main() { // The type of `john` is `serde_json::Value` let john = json!({ "name": "John Doe", "age": 43, "phones": [ "+44 1234567", "+44 2345678" ] }); println!("first phone number: {}", john["phones"][0]); // Convert to a string of JSON and print it out println!("{}", john.to_string()); }
The Value::to_string()
function converts a serde_json::Value
into a
String
of JSON text.
One neat thing about the json!
macro is that variables and expressions can
be interpolated directly into the JSON value as you are building it. Serde
will check at compile time that the value you are interpolating is able to
be represented as JSON.
let full_name = "John Doe"; let age_last_year = 42; // The type of `john` is `serde_json::Value` let john = json!({ "name": full_name, "age": age_last_year + 1, "phones": [ format!("+44 {}", random_phone()) ] });
A string of JSON data can be parsed into a serde_json::Value
by the
serde_json::from_str
function. There is also
from_slice
for parsing from a byte slice &[u8] and
from_reader
for parsing from any io::Read
like a File or
a TCP stream.
extern crate serde_json; use serde_json::{Value, Error}; fn untyped_example() -> Result<(), Error> { // Some JSON input data as a &str. Maybe this comes from the user. let data = r#"{ "name": "John Doe", "age": 43, "phones": [ "+44 1234567", "+44 2345678" ] }"#; // Parse the string of data into serde_json::Value. let v: Value = serde_json::from_str(data)?; // Access parts of the data by indexing with square brackets. println!("Please call {} at the number {}", v["name"], v["phones"][0]); Ok(()) }
Re-exports
pub use map::Map; |
Structs
Number |
Represents a JSON number, whether integer or floating point. |
Enums
Value |
Represents any valid JSON value. |
Traits
Index |
A type that can be used to index into a |
Functions
from_value |
Interpret a |
to_value |
Convert a |