1 # Serde JSON   [![Build Status]][travis] [![Latest Version]][crates.io]
3 [Build Status]: https://api.travis-ci.org/serde-rs/json.svg?branch=master
4 [travis]: https://travis-ci.org/serde-rs/json
5 [Latest Version]: https://img.shields.io/crates/v/serde_json.svg
6 [crates.io]: https://crates.io/crates/serde\_json
8 **Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.**
17 You may be looking for:
19 - [JSON API documentation](https://docs.serde.rs/serde_json/)
20 - [Serde API documentation](https://docs.serde.rs/serde/)
21 - [Detailed documentation about Serde](https://serde.rs/)
22 - [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/codegen.html)
23 - [Release notes](https://github.com/serde-rs/json/releases)
25 JSON is a ubiquitous open-standard format that uses human-readable text to
26 transmit data objects consisting of key-value pairs.
33 "street": "10 Downing Street",
43 There are three common ways that you might find yourself needing to work
44 with JSON data in Rust.
46 - **As text data.** An unprocessed string of JSON data that you receive on
47 an HTTP endpoint, read from a file, or prepare to send to a remote
49 - **As an untyped or loosely typed representation.** Maybe you want to
50 check that some JSON data is valid before passing it on, but without
51 knowing the structure of what it contains. Or you want to do very basic
52 manipulations like insert a key in a particular spot.
53 - **As a strongly typed Rust data structure.** When you expect all or most
54 of your data to conform to a particular structure and want to get real
55 work done without JSON's loosey-goosey nature tripping you up.
57 Serde JSON provides efficient, flexible, safe ways of converting data
58 between each of these representations.
60 ## Operating on untyped JSON values
62 Any valid JSON data can be manipulated in the following recursive enum
63 representation. This data structure is [`serde_json::Value`][value].
72 Object(Map<String, Value>),
76 A string of JSON data can be parsed into a `serde_json::Value` by the
77 [`serde_json::from_str`][from_str] function. There is also
78 [`from_slice`][from_slice] for parsing from a byte slice &[u8] and
79 [`from_reader`][from_reader] for parsing from any `io::Read` like a File or
82 <a href="http://play.integer32.com/?gist=a266662bc71712e080efbf25ce30f306" target="_blank">
83 <img align="right" width="50" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/run.png">
87 extern crate serde_json;
89 use serde_json::{Value, Error};
91 fn untyped_example() -> Result<(), Error> {
92 // Some JSON input data as a &str. Maybe this comes from the user.
102 // Parse the string of data into serde_json::Value.
103 let v: Value = serde_json::from_str(data)?;
105 // Access parts of the data by indexing with square brackets.
106 println!("Please call {} at the number {}", v["name"], v["phones"][0]);
112 The `Value` representation is sufficient for very basic tasks but can be tedious
113 to work with for anything more significant. Error handling is verbose to
114 implement correctly, for example imagine trying to detect the presence of
115 unrecognized fields in the input data. The compiler is powerless to help you
116 when you make a mistake, for example imagine typoing `v["name"]` as `v["nmae"]`
117 in one of the dozens of places it is used in your code.
119 ## Parsing JSON as strongly typed data structures
121 Serde provides a powerful way of mapping JSON data into Rust data structures
122 largely automatically.
124 <a href="http://play.integer32.com/?gist=cff572b80d3f078c942a2151e6020adc" target="_blank">
125 <img align="right" width="50" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/run.png">
130 extern crate serde_json;
133 extern crate serde_derive;
135 use serde_json::Error;
137 #[derive(Serialize, Deserialize)]
144 fn typed_example() -> Result<(), Error> {
145 // Some JSON input data as a &str. Maybe this comes from the user.
155 // Parse the string of data into a Person object. This is exactly the
156 // same function as the one that produced serde_json::Value above, but
157 // now we are asking it for a Person as output.
158 let p: Person = serde_json::from_str(data)?;
160 // Do things just like with any other Rust data structure.
161 println!("Please call {} at the number {}", p.name, p.phones[0]);
167 This is the same `serde_json::from_str` function as before, but this time we
168 assign the return value to a variable of type `Person` so Serde will
169 automatically interpret the input data as a `Person` and produce informative
170 error messages if the layout does not conform to what a `Person` is expected
173 Any type that implements Serde's `Deserialize` trait can be deserialized
174 this way. This includes built-in Rust standard library types like `Vec<T>`
175 and `HashMap<K, V>`, as well as any structs or enums annotated with
176 `#[derive(Deserialize)]`.
178 Once we have `p` of type `Person`, our IDE and the Rust compiler can help us
179 use it correctly like they do for any other Rust code. The IDE can
180 autocomplete field names to prevent typos, which was impossible in the
181 `serde_json::Value` representation. And the Rust compiler can check that
182 when we write `p.phones[0]`, then `p.phones` is guaranteed to be a
183 `Vec<String>` so indexing into it makes sense and produces a `String`.
185 ## Constructing JSON values
187 Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value`
188 objects with very natural JSON syntax. In order to use this macro,
189 `serde_json` needs to be imported with the `#[macro_use]` attribute.
191 <a href="http://play.integer32.com/?gist=c216d6beabd9429a6ac13b8f88938dfe" target="_blank">
192 <img align="right" width="50" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/run.png">
197 extern crate serde_json;
200 // The type of `john` is `serde_json::Value`
210 println!("first phone number: {}", john["phones"][0]);
212 // Convert to a string of JSON and print it out
213 println!("{}", john.to_string());
217 The `Value::to_string()` function converts a `serde_json::Value` into a
218 `String` of JSON text.
220 One neat thing about the `json!` macro is that variables and expressions can
221 be interpolated directly into the JSON value as you are building it. Serde
222 will check at compile time that the value you are interpolating is able to
223 be represented as JSON.
225 <a href="http://play.integer32.com/?gist=aae3af4d274bd249d1c8a947076355f2" target="_blank">
226 <img align="right" width="50" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/run.png">
230 let full_name = "John Doe";
231 let age_last_year = 42;
233 // The type of `john` is `serde_json::Value`
236 "age": age_last_year + 1,
238 format!("+44 {}", random_phone())
243 This is amazingly convenient but we have the problem we had before with
244 `Value` which is that the IDE and Rust compiler cannot help us if we get it
245 wrong. Serde JSON provides a better way of serializing strongly-typed data
246 structures into JSON text.
248 ## Creating JSON by serializing data structures
250 A data structure can be converted to a JSON string by
251 [`serde_json::to_string`][to_string]. There is also
252 [`serde_json::to_vec`][to_vec] which serializes to a `Vec<u8>` and
253 [`serde_json::to_writer`][to_writer] which serializes to any `io::Write`
254 such as a File or a TCP stream.
256 <a href="http://play.integer32.com/?gist=40967ece79921c77fd78ebc8f177c063" target="_blank">
257 <img align="right" width="50" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/run.png">
262 extern crate serde_json;
265 extern crate serde_derive;
267 use serde_json::Error;
269 #[derive(Serialize, Deserialize)]
275 fn print_an_address() -> Result<(), Error> {
276 // Some data structure.
277 let address = Address {
278 street: "10 Downing Street".to_owned(),
279 city: "London".to_owned(),
282 // Serialize it to a JSON string.
283 let j = serde_json::to_string(&address)?;
285 // Print, write to a file, or send to an HTTP server.
292 Any type that implements Serde's `Serialize` trait can be serialized this
293 way. This includes built-in Rust standard library types like `Vec<T>` and
294 `HashMap<K, V>`, as well as any structs or enums annotated with
295 `#[derive(Serialize)]`.
299 It is fast. You should expect in the ballpark of 500 to 1000 megabytes per
300 second deserialization and 600 to 900 megabytes per second serialization,
301 depending on the characteristics of your data. This is competitive with the
302 fastest C and C++ JSON libraries or even 30% faster for many use cases.
303 Benchmarks live in the [serde-rs/json-benchmark] repo.
305 [serde-rs/json-benchmark]: https://github.com/serde-rs/json-benchmark
309 Serde developers live in the #serde channel on
310 [`irc.mozilla.org`](https://wiki.mozilla.org/IRC). The #rust channel is also a
311 good resource with generally faster response time but less specific knowledge
312 about Serde. If IRC is not your thing, we are happy to respond to [GitHub
313 issues](https://github.com/serde-rs/json/issues/new) as well.
317 Serde JSON is licensed under either of
319 * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
320 http://www.apache.org/licenses/LICENSE-2.0)
321 * MIT license ([LICENSE-MIT](LICENSE-MIT) or
322 http://opensource.org/licenses/MIT)
328 Unless you explicitly state otherwise, any contribution intentionally submitted
329 for inclusion in Serde JSON by you, as defined in the Apache-2.0 license, shall
330 be dual licensed as above, without any additional terms or conditions.
332 [value]: https://docs.serde.rs/serde_json/value/enum.Value.html
333 [from_str]: https://docs.serde.rs/serde_json/de/fn.from_str.html
334 [from_slice]: https://docs.serde.rs/serde_json/de/fn.from_slice.html
335 [from_reader]: https://docs.serde.rs/serde_json/de/fn.from_reader.html
336 [to_string]: https://docs.serde.rs/serde_json/ser/fn.to_string.html
337 [to_vec]: https://docs.serde.rs/serde_json/ser/fn.to_vec.html
338 [to_writer]: https://docs.serde.rs/serde_json/ser/fn.to_writer.html
339 [macro]: https://docs.serde.rs/serde_json/macro.json.html