serde_json Documentation

repository·master·Indexed 26 days ago

https://github.com/serde-rs/json

A high-performance Rust library for serializing and deserializing data structures to and from JSON. It supports strongly typed data structures via serde::Serialize and serde::Deserialize, as well as untyped JSON values using the serde_json::Value enum. Features include the json! macro for constructing JSON, support for no-std environments with an allocator, and various parsing and serialization methods for strings, slices, and I/O streams.

Tokens
3.1K
Snippets
10
Records
15
Agent score
82%

What's inside serde_json

  1. Parse JSON into strongly typed Rust data structures

    master

    For most use cases, you should map JSON data directly into strongly typed Rust structs or enums. This provides compile-time safety, IDE autocompletion, and informative error messages if the JSON structure does not match your type.

    Requirements

    Your data structures must implement the serde::Deserialize trait. You can use #[derive(Deserialize)] to implement this automatically.

    use serde::{Deserialize, Serialize};
    use serde_json::Result;
    
    #[derive(Serialize, Deserialize)]
    struct Person {
        name: String,
        age: u8,
        phones: Vec<String>,
    }
    
    fn typed_example() -> Result<()> {
        let data = r""
            {
                "name": "John Doe",
                "age": 43,
                "phones": [
                    "+44 1234567"
                ]
            }"";
    
        // Parse the string of data into a Person object.
        let p: Person = serde_json::from_str(data)?;
    
        // Do things just like with any other Rust data structure.
        println!("Please call {} at the number {}", p.name, p.phones[0]);
    
        Ok(())
    }
  2. Find community help for Serde

    master

    If you need assistance with Serde, you can reach out to the Rust community through several channels:

    • Discord (Unofficial Community): #rust-questions or #rust-beginners channels.
    • Discord (Official Rust Project): #rust-usage or #beginners channels.
    • Zulip: #general stream on the Rust Zulip chat.
    • StackOverflow: Use the [rust] tag.
    • Reddit: /r/rust subreddit.
    • Discourse: The Rust Discourse forum.

    While you can file issues in the serde_json repository, community channels often provide faster responses.

  3. Operate on untyped JSON values using `serde_json::Value`

    master

    You can manipulate JSON data without defining a specific Rust structure by parsing it into the serde_json::Value enum. This is useful for loosely typed data or basic manipulations.

    Parsing methods

    • serde_json::from_str: Parse from a &str.
    • serde_json::from_slice: Parse from a byte slice &[u8].
    • serde_json::from_reader: Parse from any io::Read (e.g., File, TCP stream).

    Accessing data

    You can access parts of a Value using square bracket indexing (e.g., v["key"] or v[0]).

    • Indexing a map with a string key or an array with an integer key returns a &Value.
    • If the key does not exist, the index is out of bounds, or the type is incorrect, the returned element is Value::Null.
    • To get a plain Rust string instead of the JSON representation (which includes quotes), use the .as_str() method.
    use serde_json::{Result, Value};
    
    fn untyped_example() -> Result<()> {
        // Some JSON input data as a &str. Maybe this comes from the user.
        let data = r""
            {
                "name": "John Doe",
                "age": 43,
                "phones": [
                    "+44 1234567"
                ]
            }"";
    
        // 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(())
    }
  4. Enable no-std support with an allocator

    master

    You can use serde_json in no-std environments as long as a memory allocator is available. To do this, you must disable the default std feature and explicitly enable the alloc feature in your Cargo.toml.

    [dependencies]
    serde_json = { version = "1.0", default-features = false, features = ["alloc"] }
  5. Enable `no-std` support with the `alloc` feature

    master

    If you are working in a no-std environment, you can use serde_json as long as a memory allocator is available. To do this, disable the default std feature and enable the alloc feature in your Cargo.toml.

    For JSON support in environments without a memory allocator, use the serde-json-core crate instead.

    [dependencies]
    serde_json = { version = "1.0", default-features = false, features = ["alloc"] }
  6. Serialize Rust data structures to JSON

    master

    You can convert Rust data structures into JSON text using several methods. Any type implementing the serde::Serialize trait can be used.

    Serialization methods

    • serde_json::to_string: Serialize to a String.
    • serde_json::to_vec: Serialize to a Vec<u8>.
    • serde_json::to_writer: Serialize to any io::Write (e.g., File, TCP stream).
    use serde::{Deserialize, Serialize};
    use serde_json::Result;
    
    #[derive(Serialize, Deserialize)]
    struct Address {
        street: String,
        city: String,
    }
    
    fn print_an_address() -> Result<()> {
        // Some data structure.
        let address = Address {
            street: "10 Downing Street".to_owned(),
            city: "London".to_owned(),
        };
    
        // Serialize it to a JSON string.
        let j = serde_json::to_string(&address)?;
    
        // Print, write to a file, or send to an HTTP server.
        println!("{}", j);
    
        Ok(())
    }
  7. Construct JSON values with the `json!` macro

    master

    The json! macro allows you to build serde_json::Value objects using a natural JSON syntax. It supports variable and expression interpolation, and checks at compile time that the interpolated values can be represented as JSON.

    use serde_json::json;
    
    fn main() {
        // The type of `john` is `serde_json::Value`
        let john = json!({
            "name": "John Doe",
            "age": 43,
            "phones": [
                "+44 1234567"
            ]
        });
    
        println!("first phone number: {}", john["phones"][0]);
    
        // Convert to a string of JSON and print it out
        println!("{}", john.to_string());
    }
  8. Use Vec<u8> as a JSON writer

    master
    The Write trait is implemented for Vec<u8>, allowing you to use a vector as a destination for JSON serialization. This is particularly useful in no-std contexts where you need to collect serialized bytes in memory.
  9. Construct JSON values using the `json!` macro

    master

    The json! macro allows you to create serde_json::Value objects using a natural JSON-like syntax. It supports variable and expression interpolation, and checks at compile time that the interpolated values can be represented as JSON.

    use serde_json::json;
    
    fn main() {
        let john = json!({
            "name": "John Doe",
            "age": 43,
            "phones": [
                "+44 1234567",
                "+44 2345678"
            ]
        });
    
        println!("first phone number: {}", john["phones"][0]);
        println!("{}", john.to_string());
    }
  10. Mutate a `serde_json::Value` using square brackets

    master

    You can use the IndexMut implementation (the value[index] = ... syntax) to modify or insert values into a serde_json::Value.

    • Arrays: If the index is a usize, the value must be an array with a length greater than the index. If the index is out of bounds or the value is not an array, the program will panic.
    • Objects: If the index is a str or String, the value must be an object or Value::Null (which is treated as an empty object). If the key is not already present, it will be inserted with a value of Value::Null before being overwritten. If the value is neither an object nor null, the program will panic.

    Warning: Unlike read-only indexing, mutable indexing can cause panics if the underlying JSON structure does not match your expectations.

    # use serde_json::json;
    
    let mut data = json!({ "x": 0 });
    
    // replace an existing key
    data["x"] = json!(1);
    
    // insert a new key
    data["y"] = json!([false, false, false]);
    
    // replace an array value
    data["y"][0] = json!(true);
    
    // inserted a deeply nested key
    data["a"]["b"]["c"]["d"] = json!(true);