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], from_iter for parsing from an iterator of bytes, and from_reader for parsing from any io::Read like a File or a TCP stream.

use serde_json::Value;

let data = r#" { "name": "John Doe", "age": 43, ... } "#;
let v: Value = serde_json::from_str(data)?;
println!("Please call {} at the number {}", v["name"], v["phones"][0]);

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 serde_json::Value. See the get and get_mut methods of Value.

ToJson

Representation of any serializable data as a serde_json::Value.

Functions

from_value

Interpret a serde_json::Value as an instance of type T.

to_value

Convert a T into serde_json::Value which is an enum that can represent any valid JSON data.