interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / vendor / serde_json / README.md

388 lines · 14043 bytes Raw Blame History Rendered
1# Serde JSON   [![Build Status]][actions] [![Latest Version]][crates.io]
2
3[Build Status]: https://img.shields.io/github/actions/workflow/status/serde-rs/json/ci.yml?branch=master
4[actions]: https://github.com/serde-rs/json/actions?query=branch%3Amaster
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]
14serde_json = "1.0"
15```
16
17You may be looking for:
18
19- [JSON API documentation](https://docs.rs/serde_json)
20- [Serde API documentation](https://docs.rs/serde)
21- [Detailed documentation about Serde](https://serde.rs/)
22- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/derive.html)
23- [Release notes](https://github.com/serde-rs/json/releases)
24
25JSON is a ubiquitous open-standard format that uses human-readable text to
26transmit data objects consisting of key-value pairs.
27
28```json
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
43There are three common ways that you might find yourself needing to work with
44JSON data in Rust.
45
46 - **As text data.** An unprocessed string of JSON data that you receive on an
47 HTTP endpoint, read from a file, or prepare to send to a remote server.
48 - **As an untyped or loosely typed representation.** Maybe you want to check
49 that some JSON data is valid before passing it on, but without knowing the
50 structure of what it contains. Or you want to do very basic manipulations
51 like insert a key in a particular spot.
52 - **As a strongly typed Rust data structure.** When you expect all or most of
53 your data to conform to a particular structure and want to get real work done
54 without JSON's loosey-goosey nature tripping you up.
55
56Serde JSON provides efficient, flexible, safe ways of converting data between
57each of these representations.
58
59## Operating on untyped JSON values
60
61Any valid JSON data can be manipulated in the following recursive enum
62representation. This data structure is [`serde_json::Value`][value].
63
64```rust
65enum Value {
66 Null,
67 Bool(bool),
68 Number(Number),
69 String(String),
70 Array(Vec<Value>),
71 Object(Map<String, Value>),
72}
73```
74
75A string of JSON data can be parsed into a `serde_json::Value` by the
76[`serde_json::from_str`][from_str] function. There is also
77[`from_slice`][from_slice] for parsing from a byte slice `&[u8]` and
78[`from_reader`][from_reader] for parsing from any `io::Read` like a File or a
79TCP stream.
80
81<div align="right">
82<a href="https://play.rust-lang.org/?edition=2018&gist=d69d8e3156d4bb81c4461b60b772ab72" target="_blank">
83<img align="center" width="85" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/runtab.png">
84</a>
85</div>
86
87```rust
88use serde_json::{Result, Value};
89
90fn untyped_example() -> Result<()> {
91 // Some JSON input data as a &str. Maybe this comes from the user.
92 let data = r#"
93 {
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
112The result of square bracket indexing like `v["name"]` is a borrow of the data
113at that index, so the type is `&Value`. A JSON map can be indexed with string
114keys, while a JSON array can be indexed with integer keys. If the type of the
115data is not right for the type with which it is being indexed, or if a map does
116not contain the key being indexed, or if the index into a vector is out of
117bounds, the returned element is `Value::Null`.
118
119When a `Value` is printed, it is printed as a JSON string. So in the code above,
120the output looks like `Please call "John Doe" at the number "+44 1234567"`. The
121quotation marks appear because `v["name"]` is a `&Value` containing a JSON
122string and its JSON representation is `"John Doe"`. Printing as a plain string
123without quotation marks involves converting from a JSON string to a Rust string
124with [`as_str()`] or avoiding the use of `Value` as described in the following
125section.
126
127[`as_str()`]: https://docs.rs/serde_json/1/serde_json/enum.Value.html#method.as_str
128
129The `Value` representation is sufficient for very basic tasks but can be tedious
130to work with for anything more significant. Error handling is verbose to
131implement correctly, for example imagine trying to detect the presence of
132unrecognized fields in the input data. The compiler is powerless to help you
133when you make a mistake, for example imagine typoing `v["name"]` as `v["nmae"]`
134in one of the dozens of places it is used in your code.
135
136## Parsing JSON as strongly typed data structures
137
138Serde provides a powerful way of mapping JSON data into Rust data structures
139largely automatically.
140
141<div align="right">
142<a href="https://play.rust-lang.org/?edition=2018&gist=15cfab66d38ff8a15a9cf1d8d897ac68" target="_blank">
143<img align="center" width="85" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/runtab.png">
144</a>
145</div>
146
147```rust
148use serde::{Deserialize, Serialize};
149use serde_json::Result;
150
151#[derive(Serialize, Deserialize)]
152struct Person {
153 name: String,
154 age: u8,
155 phones: Vec<String>,
156}
157
158fn typed_example() -> Result<()> {
159 // Some JSON input data as a &str. Maybe this comes from the user.
160 let data = r#"
161 {
162 "name": "John Doe",
163 "age": 43,
164 "phones": [
165 "+44 1234567",
166 "+44 2345678"
167 ]
168 }"#;
169
170 // Parse the string of data into a Person object. This is exactly the
171 // same function as the one that produced serde_json::Value above, but
172 // now we are asking it for a Person as output.
173 let p: Person = serde_json::from_str(data)?;
174
175 // Do things just like with any other Rust data structure.
176 println!("Please call {} at the number {}", p.name, p.phones[0]);
177
178 Ok(())
179}
180```
181
182This is the same `serde_json::from_str` function as before, but this time we
183assign the return value to a variable of type `Person` so Serde will
184automatically interpret the input data as a `Person` and produce informative
185error messages if the layout does not conform to what a `Person` is expected to
186look like.
187
188Any type that implements Serde's `Deserialize` trait can be deserialized this
189way. This includes built-in Rust standard library types like `Vec<T>` and
190`HashMap<K, V>`, as well as any structs or enums annotated with
191`#[derive(Deserialize)]`.
192
193Once we have `p` of type `Person`, our IDE and the Rust compiler can help us use
194it correctly like they do for any other Rust code. The IDE can autocomplete
195field names to prevent typos, which was impossible in the `serde_json::Value`
196representation. And the Rust compiler can check that when we write
197`p.phones[0]`, then `p.phones` is guaranteed to be a `Vec<String>` so indexing
198into it makes sense and produces a `String`.
199
200The necessary setup for using Serde's derive macros is explained on the *[Using
201derive]* page of the Serde site.
202
203[Using derive]: https://serde.rs/derive.html
204
205## Constructing JSON values
206
207Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value`
208objects with very natural JSON syntax.
209
210<div align="right">
211<a href="https://play.rust-lang.org/?edition=2018&gist=6ccafad431d72b62e77cc34c8e879b24" target="_blank">
212<img align="center" width="85" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/runtab.png">
213</a>
214</div>
215
216```rust
217use serde_json::json;
218
219fn main() {
220 // The type of `john` is `serde_json::Value`
221 let john = json!({
222 "name": "John Doe",
223 "age": 43,
224 "phones": [
225 "+44 1234567",
226 "+44 2345678"
227 ]
228 });
229
230 println!("first phone number: {}", john["phones"][0]);
231
232 // Convert to a string of JSON and print it out
233 println!("{}", john.to_string());
234}
235```
236
237The `Value::to_string()` function converts a `serde_json::Value` into a `String`
238of JSON text.
239
240One neat thing about the `json!` macro is that variables and expressions can be
241interpolated directly into the JSON value as you are building it. Serde will
242check at compile time that the value you are interpolating is able to be
243represented as JSON.
244
245<div align="right">
246<a href="https://play.rust-lang.org/?edition=2018&gist=f9101a6e61dfc9e02c6a67f315ed24f2" target="_blank">
247<img align="center" width="85" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/runtab.png">
248</a>
249</div>
250
251```rust
252let full_name = "John Doe";
253let age_last_year = 42;
254
255// The type of `john` is `serde_json::Value`
256let john = json!({
257 "name": full_name,
258 "age": age_last_year + 1,
259 "phones": [
260 format!("+44 {}", random_phone())
261 ]
262});
263```
264
265This is amazingly convenient, but we have the problem we had before with
266`Value`: the IDE and Rust compiler cannot help us if we get it wrong. Serde JSON
267provides a better way of serializing strongly-typed data structures into JSON
268text.
269
270## Creating JSON by serializing data structures
271
272A data structure can be converted to a JSON string by
273[`serde_json::to_string`][to_string]. There is also
274[`serde_json::to_vec`][to_vec] which serializes to a `Vec<u8>` and
275[`serde_json::to_writer`][to_writer] which serializes to any `io::Write`
276such as a File or a TCP stream.
277
278<div align="right">
279<a href="https://play.rust-lang.org/?edition=2018&gist=3472242a08ed2ff88a944f2a2283b0ee" target="_blank">
280<img align="center" width="85" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/runtab.png">
281</a>
282</div>
283
284```rust
285use serde::{Deserialize, Serialize};
286use serde_json::Result;
287
288#[derive(Serialize, Deserialize)]
289struct Address {
290 street: String,
291 city: String,
292}
293
294fn print_an_address() -> Result<()> {
295 // Some data structure.
296 let address = Address {
297 street: "10 Downing Street".to_owned(),
298 city: "London".to_owned(),
299 };
300
301 // Serialize it to a JSON string.
302 let j = serde_json::to_string(&address)?;
303
304 // Print, write to a file, or send to an HTTP server.
305 println!("{}", j);
306
307 Ok(())
308}
309```
310
311Any type that implements Serde's `Serialize` trait can be serialized this way.
312This includes built-in Rust standard library types like `Vec<T>` and `HashMap<K,
313V>`, as well as any structs or enums annotated with `#[derive(Serialize)]`.
314
315## Performance
316
317It is fast. You should expect in the ballpark of 500 to 1000 megabytes per
318second deserialization and 600 to 900 megabytes per second serialization,
319depending on the characteristics of your data. This is competitive with the
320fastest C and C++ JSON libraries or even 30% faster for many use cases.
321Benchmarks live in the [serde-rs/json-benchmark] repo.
322
323[serde-rs/json-benchmark]: https://github.com/serde-rs/json-benchmark
324
325## Getting help
326
327Serde is one of the most widely used Rust libraries, so any place that
328Rustaceans congregate will be able to help you out. For chat, consider trying
329the [#rust-questions] or [#rust-beginners] channels of the unofficial community
330Discord (invite: <https://discord.gg/rust-lang-community>), the [#rust-usage] or
331[#beginners] channels of the official Rust Project Discord (invite:
332<https://discord.gg/rust-lang>), or the [#general][zulip] stream in Zulip. For
333asynchronous, consider the [\[rust\] tag on StackOverflow][stackoverflow], the
334[/r/rust] subreddit which has a pinned weekly easy questions post, or the Rust
335[Discourse forum][discourse]. It's acceptable to file a support issue in this
336repo, but they tend not to get as many eyes as any of the above and may get
337closed without a response after some time.
338
339[#rust-questions]: https://discord.com/channels/273534239310479360/274215136414400513
340[#rust-beginners]: https://discord.com/channels/273534239310479360/273541522815713281
341[#rust-usage]: https://discord.com/channels/442252698964721669/443150878111694848
342[#beginners]: https://discord.com/channels/442252698964721669/448238009733742612
343[zulip]: https://rust-lang.zulipchat.com/#narrow/stream/122651-general
344[stackoverflow]: https://stackoverflow.com/questions/tagged/rust
345[/r/rust]: https://www.reddit.com/r/rust
346[discourse]: https://users.rust-lang.org
347
348## No-std support
349
350As long as there is a memory allocator, it is possible to use serde_json without
351the rest of the Rust standard library. Disable the default "std" feature and
352enable the "alloc" feature:
353
354```toml
355[dependencies]
356serde_json = { version = "1.0", default-features = false, features = ["alloc"] }
357```
358
359For JSON support in Serde without a memory allocator, please see the
360[`serde-json-core`] crate.
361
362[`serde-json-core`]: https://github.com/rust-embedded-community/serde-json-core
363
364[value]: https://docs.rs/serde_json/1/serde_json/value/enum.Value.html
365[from_str]: https://docs.rs/serde_json/1/serde_json/de/fn.from_str.html
366[from_slice]: https://docs.rs/serde_json/1/serde_json/de/fn.from_slice.html
367[from_reader]: https://docs.rs/serde_json/1/serde_json/de/fn.from_reader.html
368[to_string]: https://docs.rs/serde_json/1/serde_json/ser/fn.to_string.html
369[to_vec]: https://docs.rs/serde_json/1/serde_json/ser/fn.to_vec.html
370[to_writer]: https://docs.rs/serde_json/1/serde_json/ser/fn.to_writer.html
371[macro]: https://docs.rs/serde_json/1/serde_json/macro.json.html
372
373<br>
374
375#### License
376
377<sup>
378Licensed under either of <a href="LICENSE-APACHE">Apache License, Version
3792.0</a> or <a href="LICENSE-MIT">MIT license</a> at your option.
380</sup>
381
382<br>
383
384<sub>
385Unless you explicitly state otherwise, any contribution intentionally submitted
386for inclusion in this crate by you, as defined in the Apache-2.0 license, shall
387be dual licensed as above, without any additional terms or conditions.
388</sub>