Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/vendor/serde_json/README.md # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers 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] 14 serde_json = "1.0" 15 ``` 16 17 You 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 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 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 with 44 JSON 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 56 Serde JSON provides efficient, flexible, safe ways of converting data between 57 each of these representations. 58 59 ## Operating on untyped JSON values 60 61 Any valid JSON data can be manipulated in the following recursive enum 62 representation. This data structure is [`serde_json::Value`][value]. 63 64 ```rust 65 enum Value { 66 Null, 67 Bool(bool), 68 Number(Number), 69 String(String), 70 Array(Vec), 71 Object(Map), 72 } 73 ``` 74 75 A 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 79 TCP stream. 80 81
82 83 84 85
86 87 ```rust 88 use serde_json::{Result, Value}; 89 90 fn 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 112 The result of square bracket indexing like `v["name"]` is a borrow of the data 113 at that index, so the type is `&Value`. A JSON map can be indexed with string 114 keys, while a JSON array can be indexed with integer keys. If the type of the 115 data is not right for the type with which it is being indexed, or if a map does 116 not contain the key being indexed, or if the index into a vector is out of 117 bounds, the returned element is `Value::Null`. 118 119 When a `Value` is printed, it is printed as a JSON string. So in the code above, 120 the output looks like `Please call "John Doe" at the number "+44 `1234567`"`. The 121 quotation marks appear because `v["name"]` is a `&Value` containing a JSON 122 string and its JSON representation is `"John Doe"`. Printing as a plain string 123 without quotation marks involves converting from a JSON string to a Rust string 124 with [`as_str()`] or avoiding the use of `Value` as described in the following 125 section. 126 127 [`as_str()`]: https://docs.rs/serde_json/1/serde_json/enum.Value.html#method.as_str 128 129 The `Value` representation is sufficient for very basic tasks but can be tedious 130 to work with for anything more significant. Error handling is verbose to 131 implement correctly, for example imagine trying to detect the presence of 132 unrecognized fields in the input data. The compiler is powerless to help you 133 when you make a mistake, for example imagine typoing `v["name"]` as `v["nmae"]` 134 in one of the dozens of places it is used in your code. 135 136 ## Parsing JSON as strongly typed data structures 137 138 Serde provides a powerful way of mapping JSON data into Rust data structures 139 largely automatically. 140 141
142 143 144 145
146 147 ```rust 148 use serde::{Deserialize, Serialize}; 149 use serde_json::Result; 150 151 #[derive(Serialize, Deserialize)] 152 struct Person { 153 name: String, 154 age: u8, 155 phones: Vec, 156 } 157 158 fn 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 182 This is the same `serde_json::from_str` function as before, but this time we 183 assign the return value to a variable of type `Person` so Serde will 184 automatically interpret the input data as a `Person` and produce informative 185 error messages if the layout does not conform to what a `Person` is expected to 186 look like. 187 188 Any type that implements Serde's `Deserialize` trait can be deserialized this 189 way. This includes built-in Rust standard library types like `Vec` and 190 `HashMap`, as well as any structs or enums annotated with 191 `#[derive(Deserialize)]`. 192 193 Once we have `p` of type `Person`, our IDE and the Rust compiler can help us use 194 it correctly like they do for any other Rust code. The IDE can autocomplete 195 field names to prevent typos, which was impossible in the `serde_json::Value` 196 representation. And the Rust compiler can check that when we write 197 `p.phones[0]`, then `p.phones` is guaranteed to be a `Vec` so indexing 198 into it makes sense and produces a `String`. 199 200 The necessary setup for using Serde's derive macros is explained on the *[Using 201 derive]* page of the Serde site. 202 203 [Using derive]: https://serde.rs/derive.html 204 205 ## Constructing JSON values 206 207 Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value` 208 objects with very natural JSON syntax. 209 210
211 212 213 214
215 216 ```rust 217 use serde_json::json; 218 219 fn 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 237 The `Value::to_string()` function converts a `serde_json::Value` into a `String` 238 of JSON text. 239 240 One neat thing about the `json!` macro is that variables and expressions can be 241 interpolated directly into the JSON value as you are building it. Serde will 242 check at compile time that the value you are interpolating is able to be 243 represented as JSON. 244 245
246 247 248 249
250 251 ```rust 252 let full_name = "John Doe"; 253 let age_last_year = 42; 254 255 // The type of `john` is `serde_json::Value` 256 let john = json!({ 257 "name": full_name, 258 "age": age_last_year + 1, 259 "phones": [ 260 format!("+44 {}", random_phone()) 261 ] 262 }); 263 ``` 264 265 This 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 267 provides a better way of serializing strongly-typed data structures into JSON 268 text. 269 270 ## Creating JSON by serializing data structures 271 272 A 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` and 275 [`serde_json::to_writer`][to_writer] which serializes to any `io::Write` 276 such as a File or a TCP stream. 277 278
279 280 281 282
283 284 ```rust 285 use serde::{Deserialize, Serialize}; 286 use serde_json::Result; 287 288 #[derive(Serialize, Deserialize)] 289 struct Address { 290 street: String, 291 city: String, 292 } 293 294 fn 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 311 Any type that implements Serde's `Serialize` trait can be serialized this way. 312 This includes built-in Rust standard library types like `Vec` and `HashMap`, as well as any structs or enums annotated with `#[derive(Serialize)]`. 314 315 ## Performance 316 317 It is fast. You should expect in the ballpark of 500 to 1000 megabytes per 318 second deserialization and 600 to 900 megabytes per second serialization, 319 depending on the characteristics of your data. This is competitive with the 320 fastest C and C++ JSON libraries or even 30% faster for many use cases. 321 Benchmarks 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 327 Serde is one of the most widely used Rust libraries, so any place that 328 Rustaceans congregate will be able to help you out. For chat, consider trying 329 the [#rust-questions] or [#rust-beginners] channels of the unofficial community 330 Discord (invite: ), the [#rust-usage] or 331 [#beginners] channels of the official Rust Project Discord (invite: 332 ), or the [#general][zulip] stream in Zulip. For 333 asynchronous, 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 336 repo, but they tend not to get as many eyes as any of the above and may get 337 closed 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 350 As long as there is a memory allocator, it is possible to use serde_json without 351 the rest of the Rust standard library. Disable the default "std" feature and 352 enable the "alloc" feature: 353 354 ```toml 355 [dependencies] 356 serde_json = { version = "1.0", default-features = false, features = ["alloc"] } 357 ``` 358 359 For 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
374 375 #### License 376 377 378 Licensed under either of Apache License, Version 379 2.0 or MIT license at your option. 380 381 382
383 384 385 Unless you explicitly state otherwise, any contribution intentionally submitted 386 for inclusion in this crate by you, as defined in the Apache-2.0 license, shall 387 be dual licensed as above, without any additional terms or conditions. 388