# serde_json 1.0.151

> JSON is a ubiquitous open-standard format that uses human-readable text to

## serde_json

### serde_json › Serde JSON

JSON is a ubiquitous open-standard format that uses human-readable text to
transmit data objects consisting of key-value pairs.

```json
{
    "name": "John Doe",
    "age": 43,
    "address": {
        "street": "10 Downing Street",
        "city": "London"
    },
    "phones": [
        "+44 1234567",
        "+44 2345678"
    ]
}
```

There are three common ways that you might find yourself needing to work
with JSON data in Rust.

 - **As text data.** An unprocessed string of JSON data that you receive on
   an HTTP endpoint, read from a file, or prepare to send to a remote
   server.
 - **As an untyped or loosely typed representation.** Maybe you want to
   check that some JSON data is valid before passing it on, but without
   knowing the structure of what it contains. Or you want to do very basic
   manipulations like insert a key in a particular spot.
 - **As a strongly typed Rust data structure.** When you expect all or most
   of your data to conform to a particular structure and want to get real
   work done without JSON's loosey-goosey nature tripping you up.

Serde JSON provides efficient, flexible, safe ways of converting data
between each of these representations.

### serde_json › Operating on untyped JSON values

Any valid JSON data can be manipulated in the following recursive enum
representation. This data structure is [`serde_json::Value`][value].

```
# use serde_json::{Number, Map};
#
# #[allow(dead_code)]
enum Value {
    Null,
    Bool(bool),
    Number(Number),
    String(String),
    Array(Vec<Value>),
    Object(Map<String, Value>),
}
```

A string of JSON data can be parsed into a `serde_json::Value` by the
[`serde_json::from_str`][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.

```
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",
                "+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(())
}
#
# fn main() {
#     untyped_example().unwrap();
# }
```

The result of square bracket indexing like `v["name"]` is a borrow of the
data at that index, so the type is `&Value`. A JSON map can be indexed with
string keys, while a JSON array can be indexed with integer keys. If the
type of the data is not right for the type with which it is being indexed,
or if a map does not contain the key being indexed, or if the index into a
vector is out of bounds, the returned element is `Value::Null`.

When a `Value` is printed, it is printed as a JSON string. So in the code
above, the output looks like `Please call "John Doe" at the number "+44
1234567"`. The quotation marks appear because `v["name"]` is a `&Value`
containing a JSON string and its JSON representation is `"John Doe"`.
Printing as a plain string without quotation marks involves converting from
a JSON string to a Rust string with [`as_str()`] or avoiding the use of
`Value` as described in the following section.

[`as_str()`]: crate::Value::as_str

The `Value` representation is sufficient for very basic tasks but can be
tedious to work with for anything more significant. Error handling is
verbose to implement correctly, for example imagine trying to detect the
presence of unrecognized fields in the input data. The compiler is powerless
to help you when you make a mistake, for example imagine typoing `v["name"]`
as `v["nmae"]` in one of the dozens of places it is used in your code.

### serde_json › Parsing JSON as strongly typed data structures

Serde provides a powerful way of mapping JSON data into Rust data structures
largely 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<()> {
    // 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 a Person object. This is exactly the
    // same function as the one that produced serde_json::Value above, but
    // now we are asking it for a Person as output.
    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(())
}
#
# fn main() {
#     typed_example().unwrap();
# }
```

This is the same `serde_json::from_str` function as before, but this time we
assign the return value to a variable of type `Person` so Serde will
automatically interpret the input data as a `Person` and produce informative
error messages if the layout does not conform to what a `Person` is expected
to look like.

Any type that implements Serde's `Deserialize` trait can be deserialized
this way. This includes built-in Rust standard library types like `Vec<T>`
and `HashMap<K, V>`, as well as any structs or enums annotated with
`#[derive(Deserialize)]`.

Once we have `p` of type `Person`, our IDE and the Rust compiler can help us
use it correctly like they do for any other Rust code. The IDE can
autocomplete field names to prevent typos, which was impossible in the
`serde_json::Value` representation. And the Rust compiler can check that
when we write `p.phones[0]`, then `p.phones` is guaranteed to be a
`Vec<String>` so indexing into it makes sense and produces a `String`.

### serde_json › Constructing JSON values

Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value`
objects with very natural JSON syntax.

```
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",
            "+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.

```
# use serde_json::json;
#
# fn random_phone() -> u16 { 0 }
#
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())
    ]
});
```

This is amazingly convenient, but we have the problem we had before with
`Value`: the IDE and Rust compiler cannot help us if we get it wrong. Serde
JSON provides a better way of serializing strongly-typed data structures
into JSON text.

### serde_json › Creating JSON by serializing data structures

A data structure can be converted to a JSON string by
[`serde_json::to_string`][to_string]. There is also
[`serde_json::to_vec`][to_vec] which serializes to a `Vec<u8>` and
[`serde_json::to_writer`][to_writer] which serializes to any `io::Write`
such as a File or a 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(())
}
#
# fn main() {
#     print_an_address().unwrap();
# }
```

Any type that implements Serde's `Serialize` trait can be serialized this
way. This includes built-in Rust standard library types like `Vec<T>` and
`HashMap<K, V>`, as well as any structs or enums annotated with
`#[derive(Serialize)]`.

### serde_json › No-std support

As long as there is a memory allocator, it is possible to use serde_json
without the rest of the Rust standard library. Disable the default "std"
feature and enable the "alloc" feature:

```toml
[dependencies]
serde_json = { version = "1.0", default-features = false, features = ["alloc"] }
```

For JSON support in Serde without a memory allocator, please see the
[`serde-json-core`] crate.

[value]: crate::value::Value
[from_str]: crate::de::from_str
[from_slice]: crate::de::from_slice
[from_reader]: crate::de::from_reader
[to_string]: crate::ser::to_string
[to_vec]: crate::ser::to_vec
[to_writer]: crate::ser::to_writer
[macro]: crate::json
[`serde-json-core`]: https://github.com/rust-embedded-community/serde-json-core

## serde_json::de (module)

Deserialize JSON data to a Rust data structure.

## serde_json::error (module)

When serializing or deserializing JSON goes wrong.

## serde_json::map (module)

A map of String to serde_json::Value.

By default the map is backed by a [`BTreeMap`]. Enable the `preserve_order`
feature of serde_json to use [`IndexMap`] instead.

[`BTreeMap`]: std::collections::BTreeMap
[`IndexMap`]: indexmap::IndexMap

## serde_json::ser (module)

Serialize a Rust data structure into JSON data.

## serde_json::value (module)

The Value enum, a loosely typed way of representing any valid JSON value.

### serde_json::value (module) › Constructing JSON

Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value`
objects with very natural JSON syntax.

```
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",
            "+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.

```
# use serde_json::json;
#
# fn random_phone() -> u16 { 0 }
#
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`][from_str] function. There is also
[`from_slice`][from_slice] for parsing from a byte slice `&[u8]` and
[`from_reader`][from_reader] for parsing from any `io::Read` like a File or
a TCP stream.

```
use serde_json::{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(())
}
#
# untyped_example().unwrap();
```

[macro]: crate::json
[from_str]: crate::de::from_str
[from_slice]: crate::de::from_slice
[from_reader]: crate::de::from_reader

## serde_json (impl)

Access an element of this map. Panics if the given key is not present in the
map.

```
# use serde_json::Value;
#
# let val = &Value::String("".to_owned());
# let _ =
match val {
    Value::String(s) => Some(s.as_str()),
    Value::Array(arr) => arr[0].as_str(),
    Value::Object(map) => map["type"].as_str(),
    _ => None,
}
# ;
```

## serde_json (impl)

Mutably access an element of this map. Panics if the given key is not
present in the map.

```
# use serde_json::json;
#
# let mut map = serde_json::Map::new();
# map.insert("key".to_owned(), serde_json::Value::Null);
#
map["key"] = json!("value");
```

## serde_json (impl)

The default value is `Value::Null`.

This is useful for handling omitted `Value` fields when deserializing.

### serde_json (impl) › Examples

```
# use serde::Deserialize;
use serde_json::Value;

#[derive(Deserialize)]
struct Settings {
    level: i32,
    #[serde(default)]
    extras: Value,
}

# fn try_main() -> Result<(), serde_json::Error> {
let data = r#" { "level": 42 } "#;
let s: Settings = serde_json::from_str(data)?;

assert_eq!(s.level, 42);
assert_eq!(s.extras, Value::Null);
#
#     Ok(())
# }
#
# try_main().unwrap()
```

## serde_json::FALSE (assoc_const)

A constant RawValue with the JSON value `false`.

## serde_json::NULL (assoc_const)

A constant RawValue with the JSON value `null`.

## serde_json::TRUE (assoc_const)

A constant RawValue with the JSON value `true`.

## serde_json::and_modify (function)

Provides in-place mutable access to an occupied entry before any
potential inserts into the map.

### serde_json::and_modify (function) › Examples

```
# use serde_json::json;
#
let mut map = serde_json::Map::new();
map.entry("serde")
    .and_modify(|e| *e = json!("rust"))
    .or_insert(json!("cpp"));

assert_eq!(map["serde"], "cpp");

map.entry("serde")
    .and_modify(|e| *e = json!("rust"))
    .or_insert(json!("cpp"));

assert_eq!(map["serde"], "rust");
```

## serde_json::append (function)

Moves all elements from other into self, leaving other empty.

## serde_json::as_array (function)

If the `Value` is an Array, returns the associated vector. Returns None
otherwise.

```
# use serde_json::json;
#
let v = json!({ "a": ["an", "array"], "b": { "an": "object" } });

// The length of `["an", "array"]` is 2 elements.
assert_eq!(v["a"].as_array().unwrap().len(), 2);

// The object `{"an": "object"}` is not an array.
assert_eq!(v["b"].as_array(), None);
```

## serde_json::as_array_mut (function)

If the `Value` is an Array, returns the associated mutable vector.
Returns None otherwise.

```
# use serde_json::json;
#
let mut v = json!({ "a": ["an", "array"] });

v["a"].as_array_mut().unwrap().clear();
assert_eq!(v, json!({ "a": [] }));
```

## serde_json::as_bool (function)

If the `Value` is a Boolean, returns the associated bool. Returns None
otherwise.

```
# use serde_json::json;
#
let v = json!({ "a": false, "b": "false" });

assert_eq!(v["a"].as_bool(), Some(false));

// The string `"false"` is a string, not a boolean.
assert_eq!(v["b"].as_bool(), None);
```

## serde_json::as_f64 (function)

If the `Value` is a number, represent it as f64 if possible. Returns
None otherwise.

```
# use serde_json::json;
#
let v = json!({ "a": 256.0, "b": 64, "c": -64 });

assert_eq!(v["a"].as_f64(), Some(256.0));
assert_eq!(v["b"].as_f64(), Some(64.0));
assert_eq!(v["c"].as_f64(), Some(-64.0));
```

## serde_json::as_f64 (function)

Represents the number as f64 if possible. Returns None otherwise.

## serde_json::as_i128 (function)

If the `Number` is an integer, represent it as i128 if possible. Returns
None otherwise.

## serde_json::as_i64 (function)

If the `Number` is an integer, represent it as i64 if possible. Returns
None otherwise.

## serde_json::as_i64 (function)

If the `Value` is an integer, represent it as i64 if possible. Returns
None otherwise.

```
# use serde_json::json;
#
let big = i64::max_value() as u64 + 10;
let v = json!({ "a": 64, "b": big, "c": 256.0 });

assert_eq!(v["a"].as_i64(), Some(64));
assert_eq!(v["b"].as_i64(), None);
assert_eq!(v["c"].as_i64(), None);
```

## serde_json::as_null (function)

If the `Value` is a Null, returns (). Returns None otherwise.

```
# use serde_json::json;
#
let v = json!({ "a": null, "b": false });

assert_eq!(v["a"].as_null(), Some(()));

// The boolean `false` is not null.
assert_eq!(v["b"].as_null(), None);
```

## serde_json::as_number (function)

If the `Value` is a Number, returns the associated [`Number`]. Returns
None otherwise.

```
# use serde_json::{json, Number};
#
let v = json!({ "a": 1, "b": 2.2, "c": -3, "d": "4" });

assert_eq!(v["a"].as_number(), Some(&Number::from(1u64)));
assert_eq!(v["b"].as_number(), Some(&Number::from_f64(2.2).unwrap()));
assert_eq!(v["c"].as_number(), Some(&Number::from(-3i64)));

// The string `"4"` is not a number.
assert_eq!(v["d"].as_number(), None);
```

## serde_json::as_object (function)

If the `Value` is an Object, returns the associated Map. Returns None
otherwise.

```
# use serde_json::json;
#
let v = json!({ "a": { "nested": true }, "b": ["an", "array"] });

// The length of `{"nested": true}` is 1 entry.
assert_eq!(v["a"].as_object().unwrap().len(), 1);

// The array `["an", "array"]` is not an object.
assert_eq!(v["b"].as_object(), None);
```

## serde_json::as_object_mut (function)

If the `Value` is an Object, returns the associated mutable Map.
Returns None otherwise.

```
# use serde_json::json;
#
let mut v = json!({ "a": { "nested": true } });

v["a"].as_object_mut().unwrap().clear();
assert_eq!(v, json!({ "a": {} }));
```

## serde_json::as_str (function)

If the `Value` is a String, returns the associated str. Returns None
otherwise.

```
# use serde_json::json;
#
let v = json!({ "a": "some string", "b": false });

assert_eq!(v["a"].as_str(), Some("some string"));

// The boolean `false` is not a string.
assert_eq!(v["b"].as_str(), None);

// JSON values are printed in JSON representation, so strings are in quotes.
//
//    The value is: "some string"
println!("The value is: {}", v["a"]);

// Rust strings are printed without quotes.
//
//    The value is: some string
println!("The value is: {}", v["a"].as_str().unwrap());
```

## serde_json::as_u128 (function)

If the `Number` is an integer, represent it as u128 if possible. Returns
None otherwise.

## serde_json::as_u64 (function)

If the `Number` is an integer, represent it as u64 if possible. Returns
None otherwise.

## serde_json::as_u64 (function)

If the `Value` is an integer, represent it as u64 if possible. Returns
None otherwise.

```
# use serde_json::json;
#
let v = json!({ "a": 64, "b": -64, "c": 256.0 });

assert_eq!(v["a"].as_u64(), Some(64));
assert_eq!(v["b"].as_u64(), None);
assert_eq!(v["c"].as_u64(), None);
```

## serde_json::begin_array (function)

Called before every array.  Writes a `[` to the specified
writer.

## serde_json::begin_array_value (function)

Called before every array value.  Writes a `,` if needed to
the specified writer.

## serde_json::begin_object (function)

Called before every object.  Writes a `{` to the specified
writer.

## serde_json::begin_object_key (function)

Called before every object key.

## serde_json::begin_object_value (function)

Called before every object value.  A `:` should be written to
the specified writer by either this method or
`end_object_key`.

## serde_json::begin_string (function)

Called before each series of `write_string_fragment` and
`write_char_escape`.  Writes a `"` to the specified writer.

## serde_json::byte_offset (function)

Returns the number of bytes so far deserialized into a successful `T`.

If a stream deserializer returns an EOF error, new data can be joined to
`old_data[stream.byte_offset()..]` to try again.

```
let data = b"[0] [1] [";

let de = serde_json::Deserializer::from_slice(data);
let mut stream = de.into_iter::<Vec<i32>>();
assert_eq!(0, stream.byte_offset());

println!("{:?}", stream.next()); // [0]
assert_eq!(3, stream.byte_offset());

println!("{:?}", stream.next()); // [1]
assert_eq!(7, stream.byte_offset());

println!("{:?}", stream.next()); // error
assert_eq!(8, stream.byte_offset());

// If err.is_eof(), can join the remaining data to new data and continue.
let remaining = &data[stream.byte_offset()..];
```

*Note:* In the future this method may be changed to return the number of
bytes so far deserialized into a successful T *or* syntactically valid
JSON skipped over due to a type error. See [serde-rs/json#70] for an
example illustrating this.

[serde-rs/json#70]: https://github.com/serde-rs/json/issues/70

## serde_json::classify (function)

Categorizes the cause of this error.

- `Category::Io` - failure to read or write bytes on an I/O stream
- `Category::Syntax` - input that is not syntactically valid JSON
- `Category::Data` - input data that is semantically incorrect
- `Category::Eof` - unexpected end of the input data

## serde_json::clear (function)

Clears the map, removing all values.

## serde_json::column (function)

One-based column number at which the error was detected.

The first character in the input and any characters immediately
following a newline character are in column 1.

Note that errors may occur in column 0, for example if a read from an
I/O stream fails immediately following a previously read newline
character.

## serde_json::contains_key (function)

Returns true if the map contains a value for the specified key.

The key may be any borrowed form of the map's key type, but the ordering
on the borrowed form *must* match the ordering on the key type.

## serde_json::de::Deserializer (struct)

A structure that deserializes JSON into Rust values.

## serde_json::de::StreamDeserializer (struct)

Iterator that deserializes a stream into multiple JSON values.

A stream deserializer can be created from any JSON deserializer using the
`Deserializer::into_iter` method.

The data can consist of any JSON value. Values need to be a self-delineating value e.g.
arrays, objects, or strings, or be followed by whitespace or a self-delineating value.

```
use serde_json::{Deserializer, Value};

fn main() {
    let data = "{\"k\": 3}1\"cool\"\"stuff\" 3{}  [0, 1, 2]";

    let stream = Deserializer::from_str(data).into_iter::<Value>();

    for value in stream {
        println!("{}", value.unwrap());
    }
}
```

## serde_json::de::from_reader (function)

Deserialize an instance of type `T` from an I/O stream of JSON.

The content of the I/O stream is deserialized directly from the stream
without being buffered in memory by serde_json.

When reading from a source against which short reads are not efficient, such
as a [`File`], you will want to apply your own buffering because serde_json
will not buffer the input. See [`std::io::BufReader`].

It is expected that the input stream ends after the deserialized object.
If the stream does not end, such as in the case of a persistent socket connection,
this function will not return. It is possible instead to deserialize from a prefix of an input
stream without looking for EOF by managing your own [`Deserializer`].

Note that counter to intuition, this function is usually slower than
reading a file completely into memory and then applying [`from_str`]
or [`from_slice`] on it. See [issue #160].

[`File`]: std::fs::File
[issue #160]: https://github.com/serde-rs/json/issues/160

### serde_json::de::from_reader (function) › Example

Reading the contents of a file.

```
use serde::Deserialize;

use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::path::Path;

#[derive(Deserialize, Debug)]
struct User {
    fingerprint: String,
    location: String,
}

fn read_user_from_file<P: AsRef<Path>>(path: P) -> Result<User, Box<dyn Error>> {
    // Open the file in read-only mode with buffer.
    let file = File::open(path)?;
    let reader = BufReader::new(file);

    // Read the JSON contents of the file as an instance of `User`.
    let u = serde_json::from_reader(reader)?;

    // Return the `User`.
    Ok(u)
}

fn main() {
# }
# fn fake_main() {
    let u = read_user_from_file("test.json").unwrap();
    println!("{:#?}", u);
}
```

Reading from a persistent socket connection.

```
use serde::Deserialize;

use std::error::Error;
use std::io::BufReader;
use std::net::{TcpListener, TcpStream};

#[derive(Deserialize, Debug)]
struct User {
    fingerprint: String,
    location: String,
}

fn read_user_from_stream(stream: &mut BufReader<TcpStream>) -> Result<User, Box<dyn Error>> {
    let mut de = serde_json::Deserializer::from_reader(stream);
    let u = User::deserialize(&mut de)?;

    Ok(u)
}

fn main() {
# }
# fn fake_main() {
    let listener = TcpListener::bind("127.0.0.1:4000").unwrap();

    for tcp_stream in listener.incoming() {
        let mut buffered = BufReader::new(tcp_stream.unwrap());
        println!("{:#?}", read_user_from_stream(&mut buffered));
    }
}
```

### serde_json::de::from_reader (function) › Errors

This conversion can fail if the structure of the input does not match the
structure expected by `T`, for example if `T` is a struct type but the input
contains something other than a JSON map. It can also fail if the structure
is correct but `T`'s implementation of `Deserialize` decides that something
is wrong with the data, for example required struct fields are missing from
the JSON map or some number is too big to fit in the expected primitive
type.

## serde_json::de::from_slice (function)

Deserialize an instance of type `T` from bytes of JSON text.

### serde_json::de::from_slice (function) › Example

```
use serde::Deserialize;

#[derive(Deserialize, Debug)]
struct User {
    fingerprint: String,
    location: String,
}

fn main() {
    // The type of `j` is `&[u8]`
    let j = b"
        {
            \"fingerprint\": \"0xF9BA143B95FF6D82\",
            \"location\": \"Menlo Park, CA\"
        }";

    let u: User = serde_json::from_slice(j).unwrap();
    println!("{:#?}", u);
}
```

### serde_json::de::from_slice (function) › Errors

This conversion can fail if the structure of the input does not match the
structure expected by `T`, for example if `T` is a struct type but the input
contains something other than a JSON map. It can also fail if the structure
is correct but `T`'s implementation of `Deserialize` decides that something
is wrong with the data, for example required struct fields are missing from
the JSON map or some number is too big to fit in the expected primitive
type.

## serde_json::de::from_str (function)

Deserialize an instance of type `T` from a string of JSON text.

### serde_json::de::from_str (function) › Example

```
use serde::Deserialize;

#[derive(Deserialize, Debug)]
struct User {
    fingerprint: String,
    location: String,
}

fn main() {
    // The type of `j` is `&str`
    let j = "
        {
            \"fingerprint\": \"0xF9BA143B95FF6D82\",
            \"location\": \"Menlo Park, CA\"
        }";

    let u: User = serde_json::from_str(j).unwrap();
    println!("{:#?}", u);
}
```

### serde_json::de::from_str (function) › Errors

This conversion can fail if the structure of the input does not match the
structure expected by `T`, for example if `T` is a struct type but the input
contains something other than a JSON map. It can also fail if the structure
is correct but `T`'s implementation of `Deserialize` decides that something
is wrong with the data, for example required struct fields are missing from
the JSON map or some number is too big to fit in the expected primitive
type.

## serde_json::deserialize_bytes (function)

Parses a JSON string as bytes. Note that this function does not check
whether the bytes represent a valid UTF-8 string.

The relevant part of the JSON specification is Section 8.2 of [RFC
7159]:

> When all the strings represented in a JSON text are composed entirely
> of Unicode characters (however escaped), then that JSON text is
> interoperable in the sense that all software implementations that
> parse it will agree on the contents of names and of string values in
> objects and arrays.
>
> However, the ABNF in this specification allows member names and string
> values to contain bit sequences that cannot encode Unicode characters;
> for example, "\uDEAD" (a single unpaired UTF-16 surrogate). Instances
> of this have been observed, for example, when a library truncates a
> UTF-16 string without checking whether the truncation split a
> surrogate pair.  The behavior of software that receives JSON texts
> containing such values is unpredictable; for example, implementations
> might return different values for the length of a string value or even
> suffer fatal runtime exceptions.

[RFC 7159]: https://tools.ietf.org/html/rfc7159

The behavior of serde_json is specified to fail on non-UTF-8 strings
when deserializing into Rust UTF-8 string types such as String, and
succeed with the bytes representing the [WTF-8] encoding of code points
when deserializing using this method.

[WTF-8]: https://simonsapin.github.io/wtf-8

Escape sequences are processed as usual, and for `\uXXXX` escapes it is
still checked if the hex number represents a valid Unicode code point.

### serde_json::deserialize_bytes (function) › Examples

You can use this to parse JSON strings containing invalid UTF-8 bytes,
or unpaired surrogates.

```
use serde_bytes::ByteBuf;

fn look_at_bytes() -> Result<(), serde_json::Error> {
    let json_data = b"\"some bytes: \xe5\x00\xe5\"";
    let bytes: ByteBuf = serde_json::from_slice(json_data)?;

    assert_eq!(b'\xe5', bytes[12]);
    assert_eq!(b'\0', bytes[13]);
    assert_eq!(b'\xe5', bytes[14]);

    Ok(())
}
#
# look_at_bytes().unwrap();
```

Backslash escape sequences like `\n` are still interpreted and required
to be valid. `\u` escape sequences are required to represent a valid
Unicode code point or lone surrogate.

```
use serde_bytes::ByteBuf;

fn look_at_bytes() -> Result<(), serde_json::Error> {
    let json_data = b"\"lone surrogate: \\uD801\"";
    let bytes: ByteBuf = serde_json::from_slice(json_data)?;
    let expected = b"lone surrogate: \xED\xA0\x81";
    assert_eq!(expected, bytes.as_slice());
    Ok(())
}
#
# look_at_bytes();
```

## serde_json::deserialize_enum (function)

Parses an enum as an object like `{"$KEY":$VALUE}`, where $VALUE is either a straight
value, a `[..]`, or a `{..}`.

## serde_json::deserialize_newtype_struct (function)

Parses a newtype struct as the underlying value.

## serde_json::deserialize_option (function)

Parses a `null` as a None, and any other values as a `Some(...)`.

## serde_json::disable_recursion_limit (function)

Parse arbitrarily deep JSON structures without any consideration for
overflowing the stack.

You will want to provide some other way to protect against stack
overflows, such as by wrapping your Deserializer in the dynamically
growing stack adapter provided by the serde_stacker crate. Additionally
you will need to be careful around other recursive operations on the
parsed result which may overflow the stack after deserialization has
completed, including, but not limited to, Display and Debug and Drop
impls.

*This method is only available if serde_json is built with the
`"unbounded_depth"` feature.*

### serde_json::disable_recursion_limit (function) › Examples

```
use serde::Deserialize;
use serde_json::Value;

fn main() {
    let mut json = String::new();
    for _ in 0..10000 {
        json = format!("[{}]", json);
    }

    let mut deserializer = serde_json::Deserializer::from_str(&json);
    deserializer.disable_recursion_limit();
    let deserializer = serde_stacker::Deserializer::new(&mut deserializer);
    let value = Value::deserialize(deserializer).unwrap();

    carefully_drop_nested_arrays(value);
}

fn carefully_drop_nested_arrays(value: Value) {
    let mut stack = vec![value];
    while let Some(value) = stack.pop() {
        if let Value::Array(array) = value {
            stack.extend(array);
        }
    }
}
```

## serde_json::end (function)

The `Deserializer::end` method should be called after a value has been fully deserialized.
This allows the `Deserializer` to validate that the input stream is at the end or that it
only has trailing whitespace.

## serde_json::end_array (function)

Called after every array.  Writes a `]` to the specified
writer.

## serde_json::end_array_value (function)

Called after every array value.

## serde_json::end_object (function)

Called after every object.  Writes a `}` to the specified
writer.

## serde_json::end_object_key (function)

Called after every object key.  A `:` should be written to the
specified writer by either this method or
`begin_object_value`.

## serde_json::end_object_value (function)

Called after every object value.

## serde_json::end_string (function)

Called after each series of `write_string_fragment` and
`write_char_escape`.  Writes a `"` to the specified writer.

## serde_json::entry (function)

Gets the given key's corresponding entry in the map for in-place
manipulation.

## serde_json::error::Category (enum)

Categorizes the cause of a `serde_json::Error`.

## serde_json::error::Category::Data (variant)

The error was caused by input data that was semantically incorrect.

For example, JSON containing a number is semantically incorrect when the
type being deserialized into holds a String.

## serde_json::error::Category::Eof (variant)

The error was caused by prematurely reaching the end of the input data.

Callers that process streaming input may be interested in retrying the
deserialization once more data is available.

## serde_json::error::Category::Io (variant)

The error was caused by a failure to read or write bytes on an I/O
stream.

## serde_json::error::Category::Syntax (variant)

The error was caused by input that was not syntactically valid JSON.

## serde_json::error::Error (struct)

This type represents all possible errors that can occur when serializing or
deserializing JSON data.

## serde_json::error::Result (type_alias)

Alias for a `Result` with the error type `serde_json::Error`.

## serde_json::fmt (function)

Display a JSON value as a string.

```
# use serde_json::json;
#
let json = json!({ "city": "London", "street": "10 Downing Street" });

// Compact format:
//
// {"city":"London","street":"10 Downing Street"}
let compact = format!("{}", json);
assert_eq!(compact,
    "{\"city\":\"London\",\"street\":\"10 Downing Street\"}");

// Pretty format:
//
// {
//   "city": "London",
//   "street": "10 Downing Street"
// }
let pretty = format!("{:#}", json);
assert_eq!(pretty,
    "{\n  \"city\": \"London\",\n  \"street\": \"10 Downing Street\"\n}");
```

## serde_json::from (function)

Convert 32-bit floating point number to `Value::Number`, or
`Value::Null` if infinite or NaN.

### serde_json::from (function) › Examples

```
use serde_json::Value;

let f: f32 = 13.37;
let x: Value = f.into();
```

## serde_json::from (function)

Convert 64-bit floating point number to `Value::Number`, or
`Value::Null` if infinite or NaN.

### serde_json::from (function) › Examples

```
use serde_json::Value;

let f: f64 = 13.37;
let x: Value = f.into();
```

## serde_json::from (function)

Convert `()` to `Value::Null`.

### serde_json::from (function) › Examples

```
use serde_json::Value;

let u = ();
let x: Value = u.into();
```

## serde_json::from (function)

Convert `Number` to `Value::Number`.

### serde_json::from (function) › Examples

```
use serde_json::{Number, Value};

let n = Number::from(7);
let x: Value = n.into();
```

## serde_json::from (function)

Convert `String` to `Value::String`.

### serde_json::from (function) › Examples

```
use serde_json::Value;

let s: String = "lorem".to_owned();
let x: Value = s.into();
```

## serde_json::from (function)

Convert a `Vec` to `Value::Array`.

### serde_json::from (function) › Examples

```
use serde_json::Value;

let v = vec!["lorem", "ipsum", "dolor"];
let x: Value = v.into();
```

## serde_json::from (function)

Convert a `serde_json::Error` into an `io::Error`.

JSON syntax and data errors are turned into `InvalidData` I/O errors.
EOF errors are turned into `UnexpectedEof` I/O errors.

```
use std::io;

enum MyError {
    Io(io::Error),
    Json(serde_json::Error),
}

impl From<serde_json::Error> for MyError {
    fn from(err: serde_json::Error) -> MyError {
        use serde_json::error::Category;
        match err.classify() {
            Category::Io => {
                MyError::Io(err.into())
            }
            Category::Syntax | Category::Data | Category::Eof => {
                MyError::Json(err)
            }
        }
    }
}
```

## serde_json::from (function)

Convert a slice to `Value::Array`.

### serde_json::from (function) › Examples

```
use serde_json::Value;

let v: &[&str] = &["lorem", "ipsum", "dolor"];
let x: Value = v.into();
```

## serde_json::from (function)

Convert boolean to `Value::Bool`.

### serde_json::from (function) › Examples

```
use serde_json::Value;

let b = false;
let x: Value = b.into();
```

## serde_json::from (function)

Convert copy-on-write string to `Value::String`.

### serde_json::from (function) › Examples

```
use serde_json::Value;
use std::borrow::Cow;

let s: Cow<str> = Cow::Borrowed("lorem");
let x: Value = s.into();
```

```
use serde_json::Value;
use std::borrow::Cow;

let s: Cow<str> = Cow::Owned("lorem".to_owned());
let x: Value = s.into();
```

## serde_json::from (function)

Convert map (with string keys) to `Value::Object`.

### serde_json::from (function) › Examples

```
use serde_json::{Map, Value};

let mut m = Map::new();
m.insert("Lorem".to_owned(), "ipsum".into());
let x: Value = m.into();
```

## serde_json::from (function)

Convert string slice to `Value::String`.

### serde_json::from (function) › Examples

```
use serde_json::Value;

let s: &str = "lorem";
let x: Value = s.into();
```

## serde_json::from_f64 (function)

Converts a finite `f64` to a `Number`. Infinite or NaN values are not JSON
numbers.

```
# use serde_json::Number;
#
assert!(Number::from_f64(256.0).is_some());

assert!(Number::from_f64(f64::NAN).is_none());
```

## serde_json::from_i128 (function)

Converts an `i128` to a `Number`. Numbers smaller than i64::MIN or
larger than u64::MAX can only be represented in `Number` if serde_json's
"arbitrary_precision" feature is enabled.

```
# use serde_json::Number;
#
assert!(Number::from_i128(256).is_some());
```

## serde_json::from_iter (function)

Create a `Value::Array` by collecting an iterator of array elements.

### serde_json::from_iter (function) › Examples

```
use serde_json::Value;

let v = std::iter::repeat(42).take(5);
let x: Value = v.collect();
```

```
use serde_json::Value;

let v: Vec<_> = vec!["lorem", "ipsum", "dolor"];
let x: Value = v.into_iter().collect();
```

```
use std::iter::FromIterator;
use serde_json::Value;

let x: Value = Value::from_iter(vec!["lorem", "ipsum", "dolor"]);
```

## serde_json::from_iter (function)

Create a `Value::Object` by collecting an iterator of key-value pairs.

### serde_json::from_iter (function) › Examples

```
use serde_json::Value;

let v: Vec<_> = vec![("lorem", 40), ("ipsum", 2)];
let x: Value = v.into_iter().collect();
```

## serde_json::from_reader (function)

Creates a JSON deserializer from an `io::Read`.

Reader-based deserializers do not support deserializing borrowed types
like `&str`, since the `std::io::Read` trait has no non-copying methods
-- everything it does involves copying bytes out of the data source.

## serde_json::from_slice (function)

Creates a JSON deserializer from a `&[u8]`.

## serde_json::from_str (function)

Creates a JSON deserializer from a `&str`.

## serde_json::from_string (function)

Convert an owned `String` of JSON data to an owned `RawValue`.

This function is equivalent to `serde_json::from_str::<Box<RawValue>>`
except that we avoid an allocation and memcpy if both of the following
are true:

- the input has no leading or trailing whitespace, and
- the input has capacity equal to its length.

## serde_json::from_string_unchecked (function)

Convert an owned `String` of JSON data to an owned `RawValue` without
checking that it contains valid JSON.

This is the unchecked counterpart of [`RawValue::from_string`], for
strings that are already known to be valid JSON, such as the output of
another JSON serializer. Unlike `from_string`, it does not re-parse the
string; the only cost is `String::into_boxed_str`.

### serde_json::from_string_unchecked (function) › Safety

The string passed in must contain a single well-formed JSON value with
no leading or trailing whitespace. `RawValue` is written verbatim into
JSON output wherever it is embedded, and other code (including unsafe
code) is allowed to rely on `RawValue` upholding this invariant, in the
same way that unsafe code may rely on `str` containing valid UTF-8.

In debug builds this contract is checked with a `debug_assert!` that
re-parses the input; the check is compiled out in release builds, so
only release performance matches the "no re-parse" guarantee above.

### serde_json::from_string_unchecked (function) › Example

```
use serde_json::value::RawValue;

let json = serde_json::to_string(&[1, 2, 3])?;

// SAFETY: `json` was produced by serde_json's own serializer, so it is
// a single well-formed JSON value without surrounding whitespace.
let raw = unsafe { RawValue::from_string_unchecked(json) };

assert_eq!(raw.get(), "[1,2,3]");
# Ok::<(), serde_json::Error>(())
```

## serde_json::from_u128 (function)

Converts a `u128` to a `Number`. Numbers greater than u64::MAX can only
be represented in `Number` if serde_json's "arbitrary_precision" feature
is enabled.

```
# use serde_json::Number;
#
assert!(Number::from_u128(256).is_some());
```

## serde_json::get (function)

Access the JSON text underlying a raw value.

### serde_json::get (function) › Example

```
use serde::Deserialize;
use serde_json::{Result, value::RawValue};

#[derive(Deserialize)]
struct Response<'a> {
    code: u32,
    #[serde(borrow)]
    payload: &'a RawValue,
}

fn process(input: &str) -> Result<()> {
    let response: Response = serde_json::from_str(input)?;

    let payload = response.payload.get();
    if payload.starts_with('{') {
        // handle a payload which is a JSON map
    } else {
        // handle any other type
    }

    Ok(())
}

fn main() -> Result<()> {
    process(r#" {"code": 200, "payload": {}} "#)?;
    Ok(())
}
```

## serde_json::get (function)

Gets a reference to the value in the entry.

### serde_json::get (function) › Examples

```
# use serde_json::json;
#
use serde_json::map::Entry;

let mut map = serde_json::Map::new();
map.insert("serde".to_owned(), json!(12));

match map.entry("serde") {
    Entry::Occupied(occupied) => {
        assert_eq!(occupied.get(), 12);
    }
    Entry::Vacant(_) => unimplemented!(),
}
```

## serde_json::get (function)

Index into a JSON array or map. A string index can be used to access a
value in a map, and a usize index can be used to access an element of an
array.

Returns `None` if the type of `self` does not match the type of the
index, for example if the index is a string and `self` is an array or a
number. Also returns `None` if the given key does not exist in the map
or the given index is not within the bounds of the array.

```
# use serde_json::json;
#
let object = json!({ "A": 65, "B": 66, "C": 67 });
assert_eq!(*object.get("A").unwrap(), json!(65));

let array = json!([ "A", "B", "C" ]);
assert_eq!(*array.get(2).unwrap(), json!("C"));

assert_eq!(array.get("A"), None);
```

Square brackets can also be used to index into a value in a more concise
way. This returns `Value::Null` in cases where `get` would have returned
`None`.

```
# use serde_json::json;
#
let object = json!({
    "A": ["a", "á", "à"],
    "B": ["b", "b́"],
    "C": ["c", "ć", "ć̣", "ḉ"],
});
assert_eq!(object["B"][0], json!("b"));

assert_eq!(object["D"], json!(null));
assert_eq!(object[0]["x"]["y"]["z"], json!(null));
```

## serde_json::get (function)

Returns a reference to the value corresponding to the key.

The key may be any borrowed form of the map's key type, but the ordering
on the borrowed form *must* match the ordering on the key type.

## serde_json::get_key_value (function)

Returns the key-value pair matching the given key.

The key may be any borrowed form of the map's key type, but the ordering
on the borrowed form *must* match the ordering on the key type.

## serde_json::get_mut (function)

Gets a mutable reference to the value in the entry.

### serde_json::get_mut (function) › Examples

```
# use serde_json::json;
#
use serde_json::map::Entry;

let mut map = serde_json::Map::new();
map.insert("serde".to_owned(), json!([1, 2, 3]));

match map.entry("serde") {
    Entry::Occupied(mut occupied) => {
        occupied.get_mut().as_array_mut().unwrap().push(json!(4));
    }
    Entry::Vacant(_) => unimplemented!(),
}

assert_eq!(map["serde"].as_array().unwrap().len(), 4);
```

## serde_json::get_mut (function)

Mutably index into a JSON array or map. A string index can be used to
access a value in a map, and a usize index can be used to access an
element of an array.

Returns `None` if the type of `self` does not match the type of the
index, for example if the index is a string and `self` is an array or a
number. Also returns `None` if the given key does not exist in the map
or the given index is not within the bounds of the array.

```
# use serde_json::json;
#
let mut object = json!({ "A": 65, "B": 66, "C": 67 });
*object.get_mut("A").unwrap() = json!(69);

let mut array = json!([ "A", "B", "C" ]);
*array.get_mut(2).unwrap() = json!("D");
```

## serde_json::get_mut (function)

Returns a mutable reference to the value corresponding to the key.

The key may be any borrowed form of the map's key type, but the ordering
on the borrowed form *must* match the ordering on the key type.

## serde_json::index (function)

Index into a `serde_json::Value` using the syntax `value[0]` or
`value["k"]`.

Returns `Value::Null` if the type of `self` does not match the type of
the index, for example if the index is a string and `self` is an array
or a number. Also returns `Value::Null` if the given key does not exist
in the map or the given index is not within the bounds of the array.

For retrieving deeply nested values, you should have a look at the
`Value::pointer` method.

### serde_json::index (function) › Examples

```
# use serde_json::json;
#
let data = json!({
    "x": {
        "y": ["z", "zz"]
    }
});

assert_eq!(data["x"]["y"], json!(["z", "zz"]));
assert_eq!(data["x"]["y"][0], json!("z"));

assert_eq!(data["a"], json!(null)); // returns null for undefined values
assert_eq!(data["a"]["b"], json!(null)); // does not panic
```

## serde_json::index_mut (function)

Write into a `serde_json::Value` using the syntax `value[0] = ...` or
`value["k"] = ...`.

If the index is a number, the value must be an array of length bigger
than the index. Indexing into a value that is not an array or an array
that is too small will panic.

If the index is a string, the value must be an object or null which is
treated like an empty object. If the key is not already present in the
object, it will be inserted with a value of null. Indexing into a value
that is neither an object nor null will panic.

### serde_json::index_mut (function) › Examples

```
# 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);

println!("{}", data);
```

## serde_json::insert (function)

Inserts a key-value pair into the map.

If the map did not have this key present, `None` is returned.

If the map did have this key present, the value is updated, and the old
value is returned.

## serde_json::insert (function)

Sets the value of the entry with the VacantEntry's key, and returns a
mutable reference to it.

### serde_json::insert (function) › Examples

```
# use serde_json::json;
#
use serde_json::map::Entry;

let mut map = serde_json::Map::new();

match map.entry("serde") {
    Entry::Vacant(vacant) => {
        vacant.insert(json!("hoho"));
    }
    Entry::Occupied(_) => unimplemented!(),
}
```

## serde_json::insert (function)

Sets the value of the entry with the `OccupiedEntry`'s key, and returns
the entry's old value.

### serde_json::insert (function) › Examples

```
# use serde_json::json;
#
use serde_json::map::Entry;

let mut map = serde_json::Map::new();
map.insert("serde".to_owned(), json!(12));

match map.entry("serde") {
    Entry::Occupied(mut occupied) => {
        assert_eq!(occupied.insert(json!(13)), 12);
        assert_eq!(occupied.get(), 13);
    }
    Entry::Vacant(_) => unimplemented!(),
}
```

## serde_json::into_inner (function)

Unwrap the `Writer` from the `Serializer`.

## serde_json::into_iter (function)

Turn a JSON deserializer into an iterator over values of type T.

## serde_json::into_mut (function)

Converts the entry into a mutable reference to its value.

### serde_json::into_mut (function) › Examples

```
# use serde_json::json;
#
use serde_json::map::Entry;

let mut map = serde_json::Map::new();
map.insert("serde".to_owned(), json!([1, 2, 3]));

match map.entry("serde") {
    Entry::Occupied(mut occupied) => {
        occupied.into_mut().as_array_mut().unwrap().push(json!(4));
    }
    Entry::Vacant(_) => unimplemented!(),
}

assert_eq!(map["serde"].as_array().unwrap().len(), 4);
```

## serde_json::into_values (function)

Gets an iterator over the values of the map.

## serde_json::io_error_kind (function)

The kind reported by the underlying standard library I/O error, if this
error was caused by a failure to read or write bytes on an I/O stream.

### serde_json::io_error_kind (function) › Example

```
use serde_json::Value;
use std::io::{self, ErrorKind, Read};
use std::process;

struct ReaderThatWillTimeOut<'a>(&'a [u8]);

impl<'a> Read for ReaderThatWillTimeOut<'a> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if self.0.is_empty() {
            Err(io::Error::new(ErrorKind::TimedOut, "timed out"))
        } else {
            self.0.read(buf)
        }
    }
}

fn main() {
    let reader = ReaderThatWillTimeOut(br#" {"k": "#);

    let _: Value = match serde_json::from_reader(reader) {
        Ok(value) => value,
        Err(error) => {
            if error.io_error_kind() == Some(ErrorKind::TimedOut) {
                // Maybe this application needs to retry certain kinds of errors.

                # return;
            } else {
                eprintln!("error: {}", error);
                process::exit(1);
            }
        }
    };
}
```

## serde_json::is_array (function)

Returns true if the `Value` is an Array. Returns false otherwise.

For any Value on which `is_array` returns true, `as_array` and
`as_array_mut` are guaranteed to return the vector representing the
array.

```
# use serde_json::json;
#
let obj = json!({ "a": ["an", "array"], "b": { "an": "object" } });

assert!(obj["a"].is_array());

// an object, not an array
assert!(!obj["b"].is_array());
```

## serde_json::is_boolean (function)

Returns true if the `Value` is a Boolean. Returns false otherwise.

For any Value on which `is_boolean` returns true, `as_bool` is
guaranteed to return the boolean value.

```
# use serde_json::json;
#
let v = json!({ "a": false, "b": "false" });

assert!(v["a"].is_boolean());

// The string `"false"` is a string, not a boolean.
assert!(!v["b"].is_boolean());
```

## serde_json::is_data (function)

Returns true if this error was caused by input data that was
semantically incorrect.

For example, JSON containing a number is semantically incorrect when the
type being deserialized into holds a String.

## serde_json::is_empty (function)

Returns true if the map contains no elements.

## serde_json::is_eof (function)

Returns true if this error was caused by prematurely reaching the end of
the input data.

Callers that process streaming input may be interested in retrying the
deserialization once more data is available.

## serde_json::is_f64 (function)

Returns true if the `Number` can be represented by f64.

For any Number on which `is_f64` returns true, `as_f64` is guaranteed to
return the floating point value.

Currently this function returns true if and only if both `is_i64` and
`is_u64` return false but this is not a guarantee in the future.

## serde_json::is_f64 (function)

Returns true if the `Value` is a number that can be represented by f64.

For any Value on which `is_f64` returns true, `as_f64` is guaranteed to
return the floating point value.

Currently this function returns true if and only if both `is_i64` and
`is_u64` return false but this is not a guarantee in the future.

```
# use serde_json::json;
#
let v = json!({ "a": 256.0, "b": 64, "c": -64 });

assert!(v["a"].is_f64());

// Integers.
assert!(!v["b"].is_f64());
assert!(!v["c"].is_f64());
```

## serde_json::is_i64 (function)

Returns true if the `Number` is an integer between `i64::MIN` and
`i64::MAX`.

For any Number on which `is_i64` returns true, `as_i64` is guaranteed to
return the integer value.

## serde_json::is_i64 (function)

Returns true if the `Value` is an integer between `i64::MIN` and
`i64::MAX`.

For any Value on which `is_i64` returns true, `as_i64` is guaranteed to
return the integer value.

```
# use serde_json::json;
#
let big = i64::max_value() as u64 + 10;
let v = json!({ "a": 64, "b": big, "c": 256.0 });

assert!(v["a"].is_i64());

// Greater than i64::MAX.
assert!(!v["b"].is_i64());

// Numbers with a decimal point are not considered integers.
assert!(!v["c"].is_i64());
```

## serde_json::is_io (function)

Returns true if this error was caused by a failure to read or write
bytes on an I/O stream.

## serde_json::is_null (function)

Returns true if the `Value` is a Null. Returns false otherwise.

For any Value on which `is_null` returns true, `as_null` is guaranteed
to return `Some(())`.

```
# use serde_json::json;
#
let v = json!({ "a": null, "b": false });

assert!(v["a"].is_null());

// The boolean `false` is not null.
assert!(!v["b"].is_null());
```

## serde_json::is_number (function)

Returns true if the `Value` is a Number. Returns false otherwise.

```
# use serde_json::json;
#
let v = json!({ "a": 1, "b": "2" });

assert!(v["a"].is_number());

// The string `"2"` is a string, not a number.
assert!(!v["b"].is_number());
```

## serde_json::is_object (function)

Returns true if the `Value` is an Object. Returns false otherwise.

For any Value on which `is_object` returns true, `as_object` and
`as_object_mut` are guaranteed to return the map representation of the
object.

```
# use serde_json::json;
#
let obj = json!({ "a": { "nested": true }, "b": ["an", "array"] });

assert!(obj.is_object());
assert!(obj["a"].is_object());

// array, not an object
assert!(!obj["b"].is_object());
```

## serde_json::is_string (function)

Returns true if the `Value` is a String. Returns false otherwise.

For any Value on which `is_string` returns true, `as_str` is guaranteed
to return the string slice.

```
# use serde_json::json;
#
let v = json!({ "a": "some string", "b": false });

assert!(v["a"].is_string());

// The boolean `false` is not a string.
assert!(!v["b"].is_string());
```

## serde_json::is_syntax (function)

Returns true if this error was caused by input that was not
syntactically valid JSON.

## serde_json::is_u64 (function)

Returns true if the `Number` is an integer between zero and `u64::MAX`.

For any Number on which `is_u64` returns true, `as_u64` is guaranteed to
return the integer value.

## serde_json::is_u64 (function)

Returns true if the `Value` is an integer between zero and `u64::MAX`.

For any Value on which `is_u64` returns true, `as_u64` is guaranteed to
return the integer value.

```
# use serde_json::json;
#
let v = json!({ "a": 64, "b": -64, "c": 256.0 });

assert!(v["a"].is_u64());

// Negative integer.
assert!(!v["b"].is_u64());

// Numbers with a decimal point are not considered integers.
assert!(!v["c"].is_u64());
```

## serde_json::iter (function)

Gets an iterator over the entries of the map.

## serde_json::iter_mut (function)

Gets a mutable iterator over the entries of the map.

## serde_json::json (macro)

Construct a `serde_json::Value` from a JSON literal.

```
# use serde_json::json;
#
let value = json!({
    "code": 200,
    "success": true,
    "payload": {
        "features": [
            "serde",
            "json"
        ],
        "homepage": null
    }
});
```

Variables or expressions can be interpolated into the JSON literal. Any type
interpolated into an array element or object value must implement Serde's
`Serialize` trait, while any type interpolated into an object key must
implement `Into<String>`. If the `Serialize` implementation of the
interpolated type decides to fail, or if the interpolated type contains a
map with non-string keys, the `json!` macro will panic.

```
# use serde_json::json;
#
let code = 200;
let features = vec!["serde", "json"];

let value = json!({
    "code": code,
    "success": code == 200,
    "payload": {
        features[0]: features[1]
    }
});
```

Trailing commas are allowed inside both arrays and objects.

```
# use serde_json::json;
#
let value = json!([
    "notice",
    "the",
    "trailing",
    "comma -->",
]);
```

## serde_json::key (function)

Gets a reference to the key in the entry.

### serde_json::key (function) › Examples

```
# use serde_json::json;
#
use serde_json::map::Entry;

let mut map = serde_json::Map::new();
map.insert("serde".to_owned(), json!(12));

match map.entry("serde") {
    Entry::Occupied(occupied) => {
        assert_eq!(occupied.key(), &"serde");
    }
    Entry::Vacant(_) => unimplemented!(),
}
```

## serde_json::key (function)

Gets a reference to the key that would be used when inserting a value
through the VacantEntry.

### serde_json::key (function) › Examples

```
use serde_json::map::Entry;

let mut map = serde_json::Map::new();

match map.entry("serde") {
    Entry::Vacant(vacant) => {
        assert_eq!(vacant.key(), &"serde");
    }
    Entry::Occupied(_) => unimplemented!(),
}
```

## serde_json::key (function)

Returns a reference to this entry's key.

### serde_json::key (function) › Examples

```
let mut map = serde_json::Map::new();
assert_eq!(map.entry("serde").key(), &"serde");
```

## serde_json::keys (function)

Gets an iterator over the keys of the map.

## serde_json::len (function)

Returns the number of elements in the map.

## serde_json::line (function)

One-based line number at which the error was detected.

Characters in the first line of the input (before the first newline
character) are in line 1.

## serde_json::map::Entry (enum)

A view into a single entry in a map, which may either be vacant or occupied.
This enum is constructed from the [`entry`] method on [`Map`].

[`entry`]: Map::entry

## serde_json::map::Entry::Occupied (variant)

An occupied Entry.

## serde_json::map::Entry::Vacant (variant)

A vacant Entry.

## serde_json::map::IntoIter (struct)

An owning iterator over a serde_json::Map's entries.

## serde_json::map::IntoValues (struct)

An owning iterator over a serde_json::Map's values.

## serde_json::map::Iter (struct)

An iterator over a serde_json::Map's entries.

## serde_json::map::IterMut (struct)

A mutable iterator over a serde_json::Map's entries.

## serde_json::map::Keys (struct)

An iterator over a serde_json::Map's keys.

## serde_json::map::Map (struct)

Represents a JSON key/value type.

## serde_json::map::OccupiedEntry (struct)

An occupied Entry. It is part of the [`Entry`] enum.

## serde_json::map::VacantEntry (struct)

A vacant Entry. It is part of the [`Entry`] enum.

## serde_json::map::Values (struct)

An iterator over a serde_json::Map's values.

## serde_json::map::ValuesMut (struct)

A mutable iterator over a serde_json::Map's values.

## serde_json::new (function)

Construct a pretty printer formatter that defaults to using two spaces for indentation.

## serde_json::new (function)

Create a JSON deserializer from one of the possible serde_json input
sources.

When reading from a source against which short reads are not efficient, such
as a [`File`], you will want to apply your own buffering because serde_json
will not buffer the input. See [`std::io::BufReader`].

Typically it is more convenient to use one of these methods instead:

  - Deserializer::from_str
  - Deserializer::from_slice
  - Deserializer::from_reader

[`File`]: std::fs::File

## serde_json::new (function)

Create a JSON input source to read from a UTF-8 string.

## serde_json::new (function)

Create a JSON input source to read from a slice of bytes.

## serde_json::new (function)

Create a JSON input source to read from a std::io input stream.

When reading from a source against which short reads are not efficient, such
as a [`File`], you will want to apply your own buffering because serde_json
will not buffer the input. See [`std::io::BufReader`].

[`File`]: std::fs::File

## serde_json::new (function)

Create a JSON stream deserializer from one of the possible serde_json
input sources.

Typically it is more convenient to use one of these methods instead:

  - Deserializer::from_str(...).into_iter()
  - Deserializer::from_slice(...).into_iter()
  - Deserializer::from_reader(...).into_iter()

## serde_json::new (function)

Creates a new JSON serializer.

## serde_json::new (function)

Makes a new empty Map.

## serde_json::number::Number (struct)

Represents a JSON number, whether integer or floating point.

## serde_json::or_insert (function)

Ensures a value is in the entry by inserting the default if empty, and
returns a mutable reference to the value in the entry.

### serde_json::or_insert (function) › Examples

```
# use serde_json::json;
#
let mut map = serde_json::Map::new();
map.entry("serde").or_insert(json!(12));

assert_eq!(map["serde"], 12);
```

## serde_json::or_insert_with (function)

Ensures a value is in the entry by inserting the result of the default
function if empty, and returns a mutable reference to the value in the
entry.

### serde_json::or_insert_with (function) › Examples

```
# use serde_json::json;
#
let mut map = serde_json::Map::new();
map.entry("serde").or_insert_with(|| json!("hoho"));

assert_eq!(map["serde"], "hoho".to_owned());
```

## serde_json::pointer (function)

Looks up a value by a JSON Pointer.

JSON Pointer defines a string syntax for identifying a specific value
within a JavaScript Object Notation (JSON) document.

A Pointer is a Unicode string with the reference tokens separated by `/`.
Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The
addressed value is returned and if there is no such value `None` is
returned.

For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).

### serde_json::pointer (function) › Examples

```
# use serde_json::json;
#
let data = json!({
    "x": {
        "y": ["z", "zz"]
    }
});

assert_eq!(data.pointer("/x/y/1").unwrap(), &json!("zz"));
assert_eq!(data.pointer("/a/b/c"), None);
```

## serde_json::pointer_mut (function)

Looks up a value by a JSON Pointer and returns a mutable reference to
that value.

JSON Pointer defines a string syntax for identifying a specific value
within a JavaScript Object Notation (JSON) document.

A Pointer is a Unicode string with the reference tokens separated by `/`.
Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The
addressed value is returned and if there is no such value `None` is
returned.

For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).

### serde_json::pointer_mut (function) › Example of Use

```
use serde_json::Value;

fn main() {
    let s = r#"{"x": 1.0, "y": 2.0}"#;
    let mut value: Value = serde_json::from_str(s).unwrap();

    // Check value using read-only pointer
    assert_eq!(value.pointer("/x"), Some(&1.0.into()));
    // Change value with direct assignment
    *value.pointer_mut("/x").unwrap() = 1.5.into();
    // Check that new value was written
    assert_eq!(value.pointer("/x"), Some(&1.5.into()));
    // Or change the value only if it exists
    value.pointer_mut("/x").map(|v| *v = 1.5.into());

    // "Steal" ownership of a value. Can replace with any valid Value.
    let old_x = value.pointer_mut("/x").map(Value::take).unwrap();
    assert_eq!(old_x, 1.5);
    assert_eq!(value.pointer("/x").unwrap(), &Value::Null);
}
```

## serde_json::pretty (function)

Creates a new JSON pretty print serializer.

## serde_json::raw::RawValue (struct)

Reference to a range of bytes encompassing a single valid JSON value in the
input data.

A `RawValue` can be used to defer parsing parts of a payload until later,
or to avoid parsing it at all in the case that part of the payload just
needs to be transferred verbatim into a different output object.

When serializing, a value of this type will retain its original formatting
and will not be minified or pretty-printed.

### serde_json::raw::RawValue (struct) › Note

`RawValue` is only available if serde\_json is built with the `"raw_value"`
feature.

```toml
[dependencies]
serde_json = { version = "1.0", features = ["raw_value"] }
```

### serde_json::raw::RawValue (struct) › Example

```
use serde::{Deserialize, Serialize};
use serde_json::{Result, value::RawValue};

#[derive(Deserialize)]
struct Input<'a> {
    code: u32,
    #[serde(borrow)]
    payload: &'a RawValue,
}

#[derive(Serialize)]
struct Output<'a> {
    info: (u32, &'a RawValue),
}

// Efficiently rearrange JSON input containing separate "code" and "payload"
// keys into a single "info" key holding an array of code and payload.
//
// This could be done equivalently using serde_json::Value as the type for
// payload, but &RawValue will perform better because it does not require
// memory allocation. The correct range of bytes is borrowed from the input
// data and pasted verbatim into the output.
fn rearrange(input: &str) -> Result<String> {
    let input: Input = serde_json::from_str(input)?;

    let output = Output {
        info: (input.code, input.payload),
    };

    serde_json::to_string(&output)
}

fn main() -> Result<()> {
    let out = rearrange(r#" {"code": 200, "payload": {}} "#)?;

    assert_eq!(out, r#"{"info":[200,{}]}"#);

    Ok(())
}
```

### serde_json::raw::RawValue (struct) › Ownership

The typical usage of `RawValue` will be in the borrowed form:

```
# use serde::Deserialize;
# use serde_json::value::RawValue;
#
#[derive(Deserialize)]
struct SomeStruct<'a> {
    #[serde(borrow)]
    raw_value: &'a RawValue,
}
```

The borrowed form is suitable when deserializing through
[`serde_json::from_str`] and [`serde_json::from_slice`] which support
borrowing from the input data without memory allocation.

When deserializing through [`serde_json::from_reader`] you will need to use
the boxed form of `RawValue` instead. This is almost as efficient but
involves buffering the raw value from the I/O stream into memory.

[`serde_json::from_str`]: crate::from_str
[`serde_json::from_slice`]: crate::from_slice
[`serde_json::from_reader`]: crate::from_reader

```
# use serde::Deserialize;
# use serde_json::value::RawValue;
#
#[derive(Deserialize)]
struct SomeStruct {
    raw_value: Box<RawValue>,
}
```

## serde_json::raw::to_raw_value (function)

Convert a `T` into a boxed `RawValue`.

### serde_json::raw::to_raw_value (function) › Example

```
// Upstream crate
# #[derive(Serialize)]
pub struct Thing {
    foo: String,
    bar: Option<String>,
    extra_data: Box<RawValue>,
}

// Local crate
use serde::Serialize;
use serde_json::value::{to_raw_value, RawValue};

#[derive(Serialize)]
struct MyExtraData {
    a: u32,
    b: u32,
}

let my_thing = Thing {
    foo: "FooVal".into(),
    bar: None,
    extra_data: to_raw_value(&MyExtraData { a: 1, b: 2 }).unwrap(),
};
# assert_eq!(
#     serde_json::to_value(my_thing).unwrap(),
#     serde_json::json!({
#         "foo": "FooVal",
#         "bar": null,
#         "extra_data": { "a": 1, "b": 2 }
#     })
# );
```

### serde_json::raw::to_raw_value (function) › Errors

This conversion can fail if `T`'s implementation of `Serialize` decides to
fail, or if `T` contains a map with non-string keys.

```
use std::collections::BTreeMap;

// The keys in this map are vectors, not strings.
let mut map = BTreeMap::new();
map.insert(vec![32, 64], "x86");

println!("{}", serde_json::value::to_raw_value(&map).unwrap_err());
```

## serde_json::read::Fused (trait)

Marker for whether StreamDeserializer can implement FusedIterator.

## serde_json::read::IoRead (struct)

JSON input source that reads from a std::io input stream.

## serde_json::read::Read (trait)

Trait used by the deserializer for iterating over input. This is manually
"specialized" for iterating over `&[u8]`. Once feature(specialization) is
stable we can use actual specialization.

This trait is sealed and cannot be implemented for types outside of
`serde_json`.

## serde_json::read::SliceRead (struct)

JSON input source that reads from a slice of bytes.

## serde_json::read::StrRead (struct)

JSON input source that reads from a UTF-8 string.

## serde_json::remove (function)

Removes a key from the map, returning the value at the key if the key
was previously in the map.

The key may be any borrowed form of the map's key type, but the ordering
on the borrowed form *must* match the ordering on the key type.

If serde_json's "preserve_order" is enabled, `.remove(key)` is
equivalent to [`.swap_remove(key)`][Self::swap_remove], replacing this
entry's position with the last element. If you need to preserve the
relative order of the keys in the map, use
[`.shift_remove(key)`][Self::shift_remove] instead.

## serde_json::remove (function)

Takes the value of the entry out of the map, and returns it.

If serde_json's "preserve_order" is enabled, `.remove()` is
equivalent to [`.swap_remove()`][Self::swap_remove], replacing this
entry's position with the last element. If you need to preserve the
relative order of the keys in the map, use
[`.shift_remove()`][Self::shift_remove] instead.

### serde_json::remove (function) › Examples

```
# use serde_json::json;
#
use serde_json::map::Entry;

let mut map = serde_json::Map::new();
map.insert("serde".to_owned(), json!(12));

match map.entry("serde") {
    Entry::Occupied(occupied) => {
        assert_eq!(occupied.remove(), 12);
    }
    Entry::Vacant(_) => unimplemented!(),
}
```

## serde_json::remove_entry (function)

Removes a key from the map, returning the stored key and value if the
key was previously in the map.

The key may be any borrowed form of the map's key type, but the ordering
on the borrowed form *must* match the ordering on the key type.

If serde_json's "preserve_order" is enabled, `.remove_entry(key)` is
equivalent to [`.swap_remove_entry(key)`][Self::swap_remove_entry],
replacing this entry's position with the last element. If you need to
preserve the relative order of the keys in the map, use
[`.shift_remove_entry(key)`][Self::shift_remove_entry] instead.

## serde_json::remove_entry (function)

Removes the entry from the map, returning the stored key and value.

If serde_json's "preserve_order" is enabled, `.remove_entry()` is
equivalent to [`.swap_remove_entry()`][Self::swap_remove_entry],
replacing this entry's position with the last element. If you need to
preserve the relative order of the keys in the map, use
[`.shift_remove_entry()`][Self::shift_remove_entry] instead.

### serde_json::remove_entry (function) › Examples

```
# use serde_json::json;
#
use serde_json::map::Entry;

let mut map = serde_json::Map::new();
map.insert("serde".to_owned(), json!(12));

match map.entry("serde") {
    Entry::Occupied(occupied) => {
        let (key, value) = occupied.remove_entry();
        assert_eq!(key, "serde");
        assert_eq!(value, 12);
    }
    Entry::Vacant(_) => unimplemented!(),
}
```

## serde_json::retain (function)

Retains only the elements specified by the predicate.

In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)`
returns `false`.

## serde_json::ser::CharEscape (enum)

Represents a character escape code in a type-safe manner.

## serde_json::ser::CharEscape::AsciiControl (variant)

An escaped ASCII plane control character (usually escaped as
`\u00XX` where `XX` are two hex characters)

## serde_json::ser::CharEscape::Backspace (variant)

An escaped backspace character (usually escaped as `\b`)

## serde_json::ser::CharEscape::CarriageReturn (variant)

An escaped carriage return character (usually escaped as `\r`)

## serde_json::ser::CharEscape::FormFeed (variant)

An escaped form feed character (usually escaped as `\f`)

## serde_json::ser::CharEscape::LineFeed (variant)

An escaped line feed character (usually escaped as `\n`)

## serde_json::ser::CharEscape::Quote (variant)

An escaped quote `"`

## serde_json::ser::CharEscape::ReverseSolidus (variant)

An escaped reverse solidus `\`

## serde_json::ser::CharEscape::Solidus (variant)

An escaped solidus `/`

## serde_json::ser::CharEscape::Tab (variant)

An escaped tab character (usually escaped as `\t`)

## serde_json::ser::CompactFormatter (struct)

This structure compacts a JSON value with no extra whitespace.

## serde_json::ser::Formatter (trait)

This trait abstracts away serializing the JSON control characters, which allows the user to
optionally pretty print the JSON output.

## serde_json::ser::PrettyFormatter (struct)

This structure pretty prints a JSON value to make it human readable.

## serde_json::ser::Serializer (struct)

A structure for serializing Rust values into JSON.

## serde_json::ser::to_string (function)

Serialize the given data structure as a String of JSON.

### serde_json::ser::to_string (function) › Errors

Serialization can fail if `T`'s implementation of `Serialize` decides to
fail, or if `T` contains a map with non-string keys.

## serde_json::ser::to_string_pretty (function)

Serialize the given data structure as a pretty-printed String of JSON.

### serde_json::ser::to_string_pretty (function) › Errors

Serialization can fail if `T`'s implementation of `Serialize` decides to
fail, or if `T` contains a map with non-string keys.

## serde_json::ser::to_vec (function)

Serialize the given data structure as a JSON byte vector.

### serde_json::ser::to_vec (function) › Errors

Serialization can fail if `T`'s implementation of `Serialize` decides to
fail, or if `T` contains a map with non-string keys.

## serde_json::ser::to_vec_pretty (function)

Serialize the given data structure as a pretty-printed JSON byte vector.

### serde_json::ser::to_vec_pretty (function) › Errors

Serialization can fail if `T`'s implementation of `Serialize` decides to
fail, or if `T` contains a map with non-string keys.

## serde_json::ser::to_writer (function)

Serialize the given data structure as JSON into the I/O stream.

Serialization guarantees it only feeds valid UTF-8 sequences to the writer.

### serde_json::ser::to_writer (function) › Errors

Serialization can fail if `T`'s implementation of `Serialize` decides to
fail, or if `T` contains a map with non-string keys.

## serde_json::ser::to_writer_pretty (function)

Serialize the given data structure as pretty-printed JSON into the I/O
stream.

Serialization guarantees it only feeds valid UTF-8 sequences to the writer.

### serde_json::ser::to_writer_pretty (function) › Errors

Serialization can fail if `T`'s implementation of `Serialize` decides to
fail, or if `T` contains a map with non-string keys.

## serde_json::serialize_newtype_struct (function)

Serialize newtypes without an object wrapper.

## serde_json::shift_insert (function)

Insert a key-value pair in the map at the given index.

If the map did not have this key present, `None` is returned.

If the map did have this key present, the key is moved to the new
position, the value is updated, and the old value is returned.

## serde_json::shift_remove (function)

Removes and returns the value corresponding to the key from the map.

Like [`Vec::remove`], the entry is removed by shifting all of the
elements that follow it, preserving their relative order. This perturbs
the index of all of those elements!

[`Vec::remove`]: std::vec::Vec::remove

## serde_json::shift_remove (function)

Takes the value of the entry out of the map, and returns it.

Like [`Vec::remove`], the entry is removed by shifting all of the
elements that follow it, preserving their relative order. This perturbs
the index of all of those elements!

[`Vec::remove`]: std::vec::Vec::remove

## serde_json::shift_remove_entry (function)

Remove and return the key-value pair.

Like [`Vec::remove`], the entry is removed by shifting all of the
elements that follow it, preserving their relative order. This perturbs
the index of all of those elements!

[`Vec::remove`]: std::vec::Vec::remove

## serde_json::shift_remove_entry (function)

Removes the entry from the map, returning the stored key and value.

Like [`Vec::remove`], the entry is removed by shifting all of the
elements that follow it, preserving their relative order. This perturbs
the index of all of those elements!

[`Vec::remove`]: std::vec::Vec::remove

## serde_json::sort_all_objects (function)

Reorders the entries of all `Value::Object` nested within this JSON
value according to `str`'s usual ordering.

If serde_json's "preserve_order" feature is not enabled, this method
does no work because all JSON maps are always kept in a sorted state.

If serde_json's "preserve_order" feature is enabled, this method
destroys the original source order or insertion order of the JSON
objects in favor of an alphanumerical order that matches how a BTreeMap
with the same contents would be ordered.

## serde_json::sort_keys (function)

Sorts this map's entries in-place using `str`'s usual ordering.

If serde_json's "preserve_order" feature is not enabled, this method
does no work because all JSON maps are always kept in a sorted state.

If serde_json's "preserve_order" feature is enabled, this method
destroys the original source order or insertion order of this map in
favor of an alphanumerical order that matches how a BTreeMap with the
same contents would be ordered. This takes **O(n log n + c)** time where
_n_ is the length of the map and _c_ is the capacity.

Other maps nested within the values of this map are not sorted. If you
need the entire data structure to be sorted at all levels, you must also
call
<code>map.[values_mut]\().for_each([Value::sort_all_objects])</code>.

[values_mut]: Map::values_mut

## serde_json::swap_remove (function)

Removes and returns the value corresponding to the key from the map.

Like [`Vec::swap_remove`], the entry is removed by swapping it with the
last element of the map and popping it off. This perturbs the position
of what used to be the last element!

[`Vec::swap_remove`]: std::vec::Vec::swap_remove

## serde_json::swap_remove (function)

Takes the value of the entry out of the map, and returns it.

Like [`Vec::swap_remove`], the entry is removed by swapping it with the
last element of the map and popping it off. This perturbs the position
of what used to be the last element!

[`Vec::swap_remove`]: std::vec::Vec::swap_remove

## serde_json::swap_remove_entry (function)

Remove and return the key-value pair.

Like [`Vec::swap_remove`], the entry is removed by swapping it with the
last element of the map and popping it off. This perturbs the position
of what used to be the last element!

[`Vec::swap_remove`]: std::vec::Vec::swap_remove

## serde_json::swap_remove_entry (function)

Removes the entry from the map, returning the stored key and value.

Like [`Vec::swap_remove`], the entry is removed by swapping it with the
last element of the map and popping it off. This perturbs the position
of what used to be the last element!

[`Vec::swap_remove`]: std::vec::Vec::swap_remove

## serde_json::take (function)

Takes the value out of the `Value`, leaving a `Null` in its place.

```
# use serde_json::json;
#
let mut v = json!({ "x": "y" });
assert_eq!(v["x"].take(), json!("y"));
assert_eq!(v, json!({ "x": null }));
```

## serde_json::value::Value (enum)

Represents any valid JSON value.

See the [`serde_json::value` module documentation](self) for usage examples.

## serde_json::value::Value::Array (variant)

Represents a JSON array.

```
# use serde_json::json;
#
let v = json!(["an", "array"]);
```

## serde_json::value::Value::Bool (variant)

Represents a JSON boolean.

```
# use serde_json::json;
#
let v = json!(true);
```

## serde_json::value::Value::Null (variant)

Represents a JSON null value.

```
# use serde_json::json;
#
let v = json!(null);
```

## serde_json::value::Value::Number (variant)

Represents a JSON number, whether integer or floating point.

```
# use serde_json::json;
#
let v = json!(12.5);
```

## serde_json::value::Value::Object (variant)

Represents a JSON object.

By default the map is backed by a BTreeMap. Enable the `preserve_order`
feature of serde_json to use IndexMap instead, which preserves
entries in the order they are inserted into the map. In particular, this
allows JSON data to be deserialized into a Value and serialized to a
string while retaining the order of map keys in the input.

```
# use serde_json::json;
#
let v = json!({ "an": "object" });
```

## serde_json::value::Value::String (variant)

Represents a JSON string.

```
# use serde_json::json;
#
let v = json!("a string");
```

## serde_json::value::from_value (function)

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

### serde_json::value::from_value (function) › Example

```
use serde::Deserialize;
use serde_json::json;

#[derive(Deserialize, Debug)]
struct User {
    fingerprint: String,
    location: String,
}

fn main() {
    // The type of `j` is `serde_json::Value`
    let j = json!({
        "fingerprint": "0xF9BA143B95FF6D82",
        "location": "Menlo Park, CA"
    });

    let u: User = serde_json::from_value(j).unwrap();
    println!("{:#?}", u);
}
```

### serde_json::value::from_value (function) › Errors

This conversion can fail if the structure of the Value does not match the
structure expected by `T`, for example if `T` is a struct type but the Value
contains something other than a JSON map. It can also fail if the structure
is correct but `T`'s implementation of `Deserialize` decides that something
is wrong with the data, for example required struct fields are missing from
the JSON map or some number is too big to fit in the expected primitive
type.

## serde_json::value::index::Index (trait)

A type that can be used to index into a `serde_json::Value`.

The [`get`] and [`get_mut`] methods of `Value` accept any type that
implements `Index`, as does the [square-bracket indexing operator]. This
trait is implemented for strings which are used as the index into a JSON
map, and for `usize` which is used as the index into a JSON array.

[`get`]: Value::get
[`get_mut`]: Value::get_mut
[square-bracket indexing operator]: Value#impl-Index%3CI%3E-for-Value

This trait is sealed and cannot be implemented for types outside of
`serde_json`.

### serde_json::value::index::Index (trait) › Examples

```
# use serde_json::json;
#
let data = json!({ "inner": [1, 2, 3] });

// Data is a JSON map so it can be indexed with a string.
let inner = &data["inner"];

// Inner is a JSON array so it can be indexed with an integer.
let first = &inner[0];

assert_eq!(first, 1);
```

## serde_json::value::ser::Serializer (struct)

Serializer whose output is a `Value`.

This is the serializer that backs [`serde_json::to_value`][crate::to_value].
Unlike the main serde_json serializer which goes from some serializable
value of type `T` to JSON text, this one goes from `T` to
`serde_json::Value`.

The `to_value` function is implementable as:

```
use serde::Serialize;
use serde_json::{Error, Value};

pub fn to_value<T>(input: T) -> Result<Value, Error>
where
    T: Serialize,
{
    input.serialize(serde_json::value::Serializer)
}
```

## serde_json::value::to_value (function)

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

### serde_json::value::to_value (function) › Example

```
use serde::Serialize;
use serde_json::json;
use std::error::Error;

#[derive(Serialize)]
struct User {
    fingerprint: String,
    location: String,
}

fn compare_json_values() -> Result<(), Box<dyn Error>> {
    let u = User {
        fingerprint: "0xF9BA143B95FF6D82".to_owned(),
        location: "Menlo Park, CA".to_owned(),
    };

    // The type of `expected` is `serde_json::Value`
    let expected = json!({
        "fingerprint": "0xF9BA143B95FF6D82",
        "location": "Menlo Park, CA",
    });

    let v = serde_json::to_value(u).unwrap();
    assert_eq!(v, expected);

    Ok(())
}
#
# compare_json_values().unwrap();
```

### serde_json::value::to_value (function) › Errors

This conversion can fail if `T`'s implementation of `Serialize` decides to
fail, or if `T` contains a map with non-string keys.

```
use std::collections::BTreeMap;

fn main() {
    // The keys in this map are vectors, not strings.
    let mut map = BTreeMap::new();
    map.insert(vec![32, 64], "x86");

    println!("{}", serde_json::to_value(map).unwrap_err());
}
```

## serde_json::values (function)

Gets an iterator over the values of the map.

## serde_json::values_mut (function)

Gets an iterator over mutable values of the map.

## serde_json::with_capacity (function)

Makes a new empty Map with the given initial capacity.

## serde_json::with_formatter (function)

Creates a new JSON visitor whose output will be written to the writer
specified.

## serde_json::with_indent (function)

Construct a pretty printer formatter that uses the `indent` string for indentation.

## serde_json::write_bool (function)

Writes a `true` or `false` value to the specified writer.

## serde_json::write_byte_array (function)

Writes the representation of a byte array. Formatters can choose whether
to represent bytes as a JSON array of integers (the default), or some
JSON string encoding like hex or base64.

## serde_json::write_char_escape (function)

Writes a character escape code to the specified writer.

## serde_json::write_f32 (function)

Writes a floating point value like `-31.26e+12` to the specified writer.

### serde_json::write_f32 (function) › Special cases

This function **does not** check for NaN or infinity. If the input
number is not a finite float, the printed representation will be some
correctly formatted but unspecified numerical value.

Please check [`is_finite`] yourself before calling this function, or
check [`is_nan`] and [`is_infinite`] and handle those cases yourself
with a different `Formatter` method.

[`is_finite`]: f32::is_finite
[`is_nan`]: f32::is_nan
[`is_infinite`]: f32::is_infinite

## serde_json::write_f64 (function)

Writes a floating point value like `-31.26e+12` to the specified writer.

### serde_json::write_f64 (function) › Special cases

This function **does not** check for NaN or infinity. If the input
number is not a finite float, the printed representation will be some
correctly formatted but unspecified numerical value.

Please check [`is_finite`] yourself before calling this function, or
check [`is_nan`] and [`is_infinite`] and handle those cases yourself
with a different `Formatter` method.

[`is_finite`]: f64::is_finite
[`is_nan`]: f64::is_nan
[`is_infinite`]: f64::is_infinite

## serde_json::write_i128 (function)

Writes an integer value like `-123` to the specified writer.

## serde_json::write_i16 (function)

Writes an integer value like `-123` to the specified writer.

## serde_json::write_i32 (function)

Writes an integer value like `-123` to the specified writer.

## serde_json::write_i64 (function)

Writes an integer value like `-123` to the specified writer.

## serde_json::write_i8 (function)

Writes an integer value like `-123` to the specified writer.

## serde_json::write_null (function)

Writes a `null` value to the specified writer.

## serde_json::write_number_str (function)

Writes a number that has already been rendered to a string.

## serde_json::write_raw_fragment (function)

Writes a raw JSON fragment that doesn't need any escaping to the
specified writer.

## serde_json::write_string_fragment (function)

Writes a string fragment that doesn't need any escaping to the
specified writer.

## serde_json::write_u128 (function)

Writes an integer value like `123` to the specified writer.

## serde_json::write_u16 (function)

Writes an integer value like `123` to the specified writer.

## serde_json::write_u32 (function)

Writes an integer value like `123` to the specified writer.

## serde_json::write_u64 (function)

Writes an integer value like `123` to the specified writer.

## serde_json::write_u8 (function)

Writes an integer value like `123` to the specified writer.

