]> git.proxmox.com Git - cargo.git/blob - vendor/serde_json-1.0.3/README.md
New upstream version 0.23.0
[cargo.git] / vendor / serde_json-1.0.3 / README.md
1 # Serde JSON   [![Build Status]][travis] [![Latest Version]][crates.io]
2
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
7
8 **Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.**
9
10 ---
11
12 ```toml
13 [dependencies]
14 serde_json = "1.0"
15 ```
16
17 You may be looking for:
18
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)
24
25 JSON is a ubiquitous open-standard format that uses human-readable text to
26 transmit data objects consisting of key-value pairs.
27
28 ```json,ignore
29 {
30 "name": "John Doe",
31 "age": 43,
32 "address": {
33 "street": "10 Downing Street",
34 "city": "London"
35 },
36 "phones": [
37 "+44 1234567",
38 "+44 2345678"
39 ]
40 }
41 ```
42
43 There are three common ways that you might find yourself needing to work
44 with JSON data in Rust.
45
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
48 server.
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.
56
57 Serde JSON provides efficient, flexible, safe ways of converting data
58 between each of these representations.
59
60 ## Operating on untyped JSON values
61
62 Any valid JSON data can be manipulated in the following recursive enum
63 representation. This data structure is [`serde_json::Value`][value].
64
65 ```rust,ignore
66 enum Value {
67 Null,
68 Bool(bool),
69 Number(Number),
70 String(String),
71 Array(Vec<Value>),
72 Object(Map<String, Value>),
73 }
74 ```
75
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
80 a TCP stream.
81
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">
84 </a>
85
86 ```rust
87 extern crate serde_json;
88
89 use serde_json::{Value, Error};
90
91 fn untyped_example() -> Result<(), Error> {
92 // Some JSON input data as a &str. Maybe this comes from the user.
93 let data = r#"{
94 "name": "John Doe",
95 "age": 43,
96 "phones": [
97 "+44 1234567",
98 "+44 2345678"
99 ]
100 }"#;
101
102 // Parse the string of data into serde_json::Value.
103 let v: Value = serde_json::from_str(data)?;
104
105 // Access parts of the data by indexing with square brackets.
106 println!("Please call {} at the number {}", v["name"], v["phones"][0]);
107
108 Ok(())
109 }
110 ```
111
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.
118
119 ## Parsing JSON as strongly typed data structures
120
121 Serde provides a powerful way of mapping JSON data into Rust data structures
122 largely automatically.
123
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">
126 </a>
127
128 ```rust
129 extern crate serde;
130 extern crate serde_json;
131
132 #[macro_use]
133 extern crate serde_derive;
134
135 use serde_json::Error;
136
137 #[derive(Serialize, Deserialize)]
138 struct Person {
139 name: String,
140 age: u8,
141 phones: Vec<String>,
142 }
143
144 fn typed_example() -> Result<(), Error> {
145 // Some JSON input data as a &str. Maybe this comes from the user.
146 let data = r#"{
147 "name": "John Doe",
148 "age": 43,
149 "phones": [
150 "+44 1234567",
151 "+44 2345678"
152 ]
153 }"#;
154
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)?;
159
160 // Do things just like with any other Rust data structure.
161 println!("Please call {} at the number {}", p.name, p.phones[0]);
162
163 Ok(())
164 }
165 ```
166
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
171 to look like.
172
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)]`.
177
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`.
184
185 ## Constructing JSON values
186
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.
190
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">
193 </a>
194
195 ```rust
196 #[macro_use]
197 extern crate serde_json;
198
199 fn main() {
200 // The type of `john` is `serde_json::Value`
201 let john = json!({
202 "name": "John Doe",
203 "age": 43,
204 "phones": [
205 "+44 1234567",
206 "+44 2345678"
207 ]
208 });
209
210 println!("first phone number: {}", john["phones"][0]);
211
212 // Convert to a string of JSON and print it out
213 println!("{}", john.to_string());
214 }
215 ```
216
217 The `Value::to_string()` function converts a `serde_json::Value` into a
218 `String` of JSON text.
219
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.
224
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">
227 </a>
228
229 ```rust
230 let full_name = "John Doe";
231 let age_last_year = 42;
232
233 // The type of `john` is `serde_json::Value`
234 let john = json!({
235 "name": full_name,
236 "age": age_last_year + 1,
237 "phones": [
238 format!("+44 {}", random_phone())
239 ]
240 });
241 ```
242
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.
247
248 ## Creating JSON by serializing data structures
249
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.
255
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">
258 </a>
259
260 ```rust
261 extern crate serde;
262 extern crate serde_json;
263
264 #[macro_use]
265 extern crate serde_derive;
266
267 use serde_json::Error;
268
269 #[derive(Serialize, Deserialize)]
270 struct Address {
271 street: String,
272 city: String,
273 }
274
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(),
280 };
281
282 // Serialize it to a JSON string.
283 let j = serde_json::to_string(&address)?;
284
285 // Print, write to a file, or send to an HTTP server.
286 println!("{}", j);
287
288 Ok(())
289 }
290 ```
291
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)]`.
296
297 ## Performance
298
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.
304
305 [serde-rs/json-benchmark]: https://github.com/serde-rs/json-benchmark
306
307 ## Getting help
308
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.
314
315 ## License
316
317 Serde JSON is licensed under either of
318
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)
323
324 at your option.
325
326 ### Contribution
327
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.
331
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