1 // Copyright 2017 Serde Developers
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
11 //! JSON is a ubiquitous open-standard format that uses human-readable text to
12 //! transmit data objects consisting of key-value pairs.
16 //! "name": "John Doe",
19 //! "street": "10 Downing Street",
29 //! There are three common ways that you might find yourself needing to work
30 //! with JSON data in Rust.
32 //! - **As text data.** An unprocessed string of JSON data that you receive on
33 //! an HTTP endpoint, read from a file, or prepare to send to a remote
35 //! - **As an untyped or loosely typed representation.** Maybe you want to
36 //! check that some JSON data is valid before passing it on, but without
37 //! knowing the structure of what it contains. Or you want to do very basic
38 //! manipulations like insert a key in a particular spot.
39 //! - **As a strongly typed Rust data structure.** When you expect all or most
40 //! of your data to conform to a particular structure and want to get real
41 //! work done without JSON's loosey-goosey nature tripping you up.
43 //! Serde JSON provides efficient, flexible, safe ways of converting data
44 //! between each of these representations.
46 //! # Operating on untyped JSON values
48 //! Any valid JSON data can be manipulated in the following recursive enum
49 //! representation. This data structure is [`serde_json::Value`][value].
52 //! # use serde_json::{Number, Map};
54 //! # #[allow(dead_code)]
60 //! Array(Vec<Value>),
61 //! Object(Map<String, Value>),
65 //! A string of JSON data can be parsed into a `serde_json::Value` by the
66 //! [`serde_json::from_str`][from_str] function. There is also
67 //! [`from_slice`][from_slice] for parsing from a byte slice &[u8] and
68 //! [`from_reader`][from_reader] for parsing from any `io::Read` like a File or
72 //! extern crate serde_json;
74 //! use serde_json::{Value, Error};
76 //! fn untyped_example() -> Result<(), Error> {
77 //! // Some JSON input data as a &str. Maybe this comes from the user.
79 //! "name": "John Doe",
87 //! // Parse the string of data into serde_json::Value.
88 //! let v: Value = serde_json::from_str(data)?;
90 //! // Access parts of the data by indexing with square brackets.
91 //! println!("Please call {} at the number {}", v["name"], v["phones"][0]);
97 //! # untyped_example().unwrap();
101 //! The result of square bracket indexing like `v["name"]` is a borrow of the
102 //! data at that index, so the type is `&Value`. A JSON map can be indexed with
103 //! string keys, while a JSON array can be indexed with integer keys. If the
104 //! type of the data is not right for the type with which it is being indexed,
105 //! or if a map does not contain the key being indexed, or if the index into a
106 //! vector is out of bounds, the returned element is `Value::Null`.
108 //! When a `Value` is printed, it is printed as a JSON string. So in the code
109 //! above, the output looks like `Please call "John Doe" at the number "+44
110 //! 1234567"`. The quotation marks appear because `v["name"]` is a `&Value`
111 //! containing a JSON string and its JSON representation is `"John Doe"`.
112 //! Printing as a plain string without quotation marks involves converting from
113 //! a JSON string to a Rust string with [`as_str()`] or avoiding the use of
114 //! `Value` as described in the following section.
116 //! [`as_str()`]: https://docs.serde.rs/serde_json/enum.Value.html#method.as_str
118 //! The `Value` representation is sufficient for very basic tasks but can be
119 //! tedious to work with for anything more significant. Error handling is
120 //! verbose to implement correctly, for example imagine trying to detect the
121 //! presence of unrecognized fields in the input data. The compiler is powerless
122 //! to help you when you make a mistake, for example imagine typoing `v["name"]`
123 //! as `v["nmae"]` in one of the dozens of places it is used in your code.
125 //! # Parsing JSON as strongly typed data structures
127 //! Serde provides a powerful way of mapping JSON data into Rust data structures
128 //! largely automatically.
131 //! extern crate serde;
132 //! extern crate serde_json;
135 //! extern crate serde_derive;
137 //! use serde_json::Error;
139 //! #[derive(Serialize, Deserialize)]
143 //! phones: Vec<String>,
146 //! fn typed_example() -> Result<(), Error> {
147 //! // Some JSON input data as a &str. Maybe this comes from the user.
149 //! "name": "John Doe",
157 //! // Parse the string of data into a Person object. This is exactly the
158 //! // same function as the one that produced serde_json::Value above, but
159 //! // now we are asking it for a Person as output.
160 //! let p: Person = serde_json::from_str(data)?;
162 //! // Do things just like with any other Rust data structure.
163 //! println!("Please call {} at the number {}", p.name, p.phones[0]);
169 //! # typed_example().unwrap();
173 //! This is the same `serde_json::from_str` function as before, but this time we
174 //! assign the return value to a variable of type `Person` so Serde will
175 //! automatically interpret the input data as a `Person` and produce informative
176 //! error messages if the layout does not conform to what a `Person` is expected
179 //! Any type that implements Serde's `Deserialize` trait can be deserialized
180 //! this way. This includes built-in Rust standard library types like `Vec<T>`
181 //! and `HashMap<K, V>`, as well as any structs or enums annotated with
182 //! `#[derive(Deserialize)]`.
184 //! Once we have `p` of type `Person`, our IDE and the Rust compiler can help us
185 //! use it correctly like they do for any other Rust code. The IDE can
186 //! autocomplete field names to prevent typos, which was impossible in the
187 //! `serde_json::Value` representation. And the Rust compiler can check that
188 //! when we write `p.phones[0]`, then `p.phones` is guaranteed to be a
189 //! `Vec<String>` so indexing into it makes sense and produces a `String`.
191 //! # Constructing JSON values
193 //! Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value`
194 //! objects with very natural JSON syntax. In order to use this macro,
195 //! `serde_json` needs to be imported with the `#[macro_use]` attribute.
199 //! extern crate serde_json;
202 //! // The type of `john` is `serde_json::Value`
203 //! let john = json!({
204 //! "name": "John Doe",
212 //! println!("first phone number: {}", john["phones"][0]);
214 //! // Convert to a string of JSON and print it out
215 //! println!("{}", john.to_string());
219 //! The `Value::to_string()` function converts a `serde_json::Value` into a
220 //! `String` of JSON text.
222 //! One neat thing about the `json!` macro is that variables and expressions can
223 //! be interpolated directly into the JSON value as you are building it. Serde
224 //! will check at compile time that the value you are interpolating is able to
225 //! be represented as JSON.
229 //! # extern crate serde_json;
231 //! # fn random_phone() -> u16 { 0 }
234 //! let full_name = "John Doe";
235 //! let age_last_year = 42;
237 //! // The type of `john` is `serde_json::Value`
238 //! let john = json!({
239 //! "name": full_name,
240 //! "age": age_last_year + 1,
242 //! format!("+44 {}", random_phone())
249 //! This is amazingly convenient but we have the problem we had before with
250 //! `Value` which is that the IDE and Rust compiler cannot help us if we get it
251 //! wrong. Serde JSON provides a better way of serializing strongly-typed data
252 //! structures into JSON text.
254 //! # Creating JSON by serializing data structures
256 //! A data structure can be converted to a JSON string by
257 //! [`serde_json::to_string`][to_string]. There is also
258 //! [`serde_json::to_vec`][to_vec] which serializes to a `Vec<u8>` and
259 //! [`serde_json::to_writer`][to_writer] which serializes to any `io::Write`
260 //! such as a File or a TCP stream.
263 //! extern crate serde;
264 //! extern crate serde_json;
267 //! extern crate serde_derive;
269 //! use serde_json::Error;
271 //! #[derive(Serialize, Deserialize)]
277 //! fn print_an_address() -> Result<(), Error> {
278 //! // Some data structure.
279 //! let address = Address {
280 //! street: "10 Downing Street".to_owned(),
281 //! city: "London".to_owned(),
284 //! // Serialize it to a JSON string.
285 //! let j = serde_json::to_string(&address)?;
287 //! // Print, write to a file, or send to an HTTP server.
288 //! println!("{}", j);
294 //! # print_an_address().unwrap();
298 //! Any type that implements Serde's `Serialize` trait can be serialized this
299 //! way. This includes built-in Rust standard library types like `Vec<T>` and
300 //! `HashMap<K, V>`, as well as any structs or enums annotated with
301 //! `#[derive(Serialize)]`.
305 //! This crate currently requires the Rust standard library. For JSON support in
306 //! Serde without a standard library, please see the [`serde-json-core`] crate.
308 //! [value]: https://docs.serde.rs/serde_json/value/enum.Value.html
309 //! [from_str]: https://docs.serde.rs/serde_json/de/fn.from_str.html
310 //! [from_slice]: https://docs.serde.rs/serde_json/de/fn.from_slice.html
311 //! [from_reader]: https://docs.serde.rs/serde_json/de/fn.from_reader.html
312 //! [to_string]: https://docs.serde.rs/serde_json/ser/fn.to_string.html
313 //! [to_vec]: https://docs.serde.rs/serde_json/ser/fn.to_vec.html
314 //! [to_writer]: https://docs.serde.rs/serde_json/ser/fn.to_writer.html
315 //! [macro]: https://docs.serde.rs/serde_json/macro.json.html
316 //! [`serde-json-core`]: https://japaric.github.io/serde-json-core/serde_json_core/
318 #![doc(html_root_url = "https://docs.rs/serde_json/1.0.15")]
319 #![cfg_attr(feature = "cargo-clippy", deny(clippy, clippy_pedantic))]
320 // Whitelisted clippy lints
321 #![cfg_attr(feature = "cargo-clippy", allow(doc_markdown, needless_pass_by_value))]
322 // Whitelisted clippy_pedantic lints
323 #![cfg_attr(feature = "cargo-clippy", allow(
324 // Deserializer::from_str, into_iter
325 should_implement_trait
,
326 // integer and float ser/de requires these sorts of casts
327 cast_possible_truncation
,
331 // string ser/de uses indexing and slicing
333 // things are often more readable this way
341 missing_docs_in_private_items
,
343 // we support older compilers
344 redundant_field_names
,
346 #![deny(missing_docs)]
348 extern crate num_traits
;
353 #[cfg(feature = "preserve_order")]
354 extern crate linked_hash_map
;
357 pub use self::de
::{from_reader, from_slice, from_str, Deserializer, StreamDeserializer}
;
359 pub use self::error
::{Error, Result}
;
361 pub use self::ser
::{to_string
, to_string_pretty
, to_vec
, to_vec_pretty
, to_writer
,
362 to_writer_pretty
, Serializer
};
364 pub use self::value
::{from_value, to_value, Map, Number, Value}
;
366 // We only use our own error type; no need for From conversions provided by the
367 // standard library's try! macro. This reduces lines of LLVM IR by 4%.
371 ::std
::result
::Result
::Ok(val
) => val
,
372 ::std
::result
::Result
::Err(err
) => return ::std
::result
::Result
::Err(err
),