Skip to content

Commit d9b7da9

Browse files
committed
Merge branch 'origin/master' into 'origin/1.0'
2 parents 0eca1ad + ac1e28f commit d9b7da9

File tree

3 files changed

+188
-81
lines changed

3 files changed

+188
-81
lines changed

README.md

Lines changed: 84 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,15 @@ with JSON data in Rust.
4444
- **As an untyped or loosely typed representation.** Maybe you want to
4545
check that some JSON data is valid before passing it on, but without
4646
knowing the structure of what it contains. Or you want to do very basic
47-
manipulations like add a level of nesting.
47+
manipulations like insert a key in a particular spot.
4848
- **As a strongly typed Rust data structure.** When you expect all or most
4949
of your data to conform to a particular structure and want to get real
5050
work done without JSON's loosey-goosey nature tripping you up.
5151

5252
Serde JSON provides efficient, flexible, safe ways of converting data
5353
between each of these representations.
5454

55-
## JSON to the Value enum
55+
## Operating on untyped JSON values
5656

5757
Any valid JSON data can be manipulated in the following recursive enum
5858
representation. This data structure is [`serde_json::Value`][value].
@@ -76,47 +76,84 @@ A string of JSON data can be parsed into a `serde_json::Value` by the
7676
a TCP stream.
7777

7878
```rust
79-
use serde_json::Value;
79+
extern crate serde_json;
80+
81+
use serde_json::{Value, Error};
82+
83+
fn untyped_example() -> Result<(), Error> {
84+
// Some JSON input data as a &str. Maybe this comes from the user.
85+
let data = r#"{
86+
"name": "John Doe",
87+
"age": 43,
88+
"phones": [
89+
"+44 1234567",
90+
"+44 2345678"
91+
]
92+
}"#;
8093

81-
let data = r#" { "name": "John Doe", "age": 43, ... } "#;
82-
let v: Value = serde_json::from_str(data)?;
83-
println!("Please call {} at the number {}", v["name"], v["phones"][0]);
94+
// Parse the string of data into serde_json::Value.
95+
let v: Value = serde_json::from_str(data)?;
96+
97+
// Access parts of the data by indexing with square brackets.
98+
println!("Please call {} at the number {}", v["name"], v["phones"][0]);
99+
100+
Ok(())
101+
}
84102
```
85103

86-
The `Value` representation is sufficient for very basic tasks but is brittle
87-
and tedious to work with. Error handling is verbose to implement correctly,
88-
for example imagine trying to detect the presence of unrecognized fields in
89-
the input data. The compiler is powerless to help you when you make a
90-
mistake, for example imagine typoing `v["name"]` as `v["nmae"]` in one of
91-
the dozens of places it is used in your code.
104+
The `Value` representation is sufficient for very basic tasks but can be tedious
105+
to work with for anything more significant. Error handling is verbose to
106+
implement correctly, for example imagine trying to detect the presence of
107+
unrecognized fields in the input data. The compiler is powerless to help you
108+
when you make a mistake, for example imagine typoing `v["name"]` as `v["nmae"]`
109+
in one of the dozens of places it is used in your code.
92110

93-
## JSON to strongly typed data structures
111+
## Parsing JSON as strongly typed data structures
94112

95113
Serde provides a powerful way of mapping JSON data into Rust data structures
96114
largely automatically.
97115

98116
```rust
117+
extern crate serde;
118+
extern crate serde_json;
119+
120+
#[macro_use]
121+
extern crate serde_derive;
122+
123+
use serde_json::Error;
124+
99125
#[derive(Serialize, Deserialize)]
100126
struct Person {
101127
name: String,
102128
age: u8,
103-
address: Address,
104129
phones: Vec<String>,
105130
}
106131

107-
#[derive(Serialize, Deserialize)]
108-
struct Address {
109-
street: String,
110-
city: String,
132+
fn typed_example() -> Result<(), Error> {
133+
// Some JSON input data as a &str. Maybe this comes from the user.
134+
let data = r#"{
135+
"name": "John Doe",
136+
"age": 43,
137+
"phones": [
138+
"+44 1234567",
139+
"+44 2345678"
140+
]
141+
}"#;
142+
143+
// Parse the string of data into a Person object. This is exactly the
144+
// same function as the one that produced serde_json::Value above, but
145+
// now we are asking it for a Person as output.
146+
let p: Person = serde_json::from_str(data)?;
147+
148+
// Do things just like with any other Rust data structure.
149+
println!("Please call {} at the number {}", p.name, p.phones[0]);
150+
151+
Ok(())
111152
}
112-
113-
let data = r#" { "name": "John Doe", "age": 43, ... } "#;
114-
let p: Person = serde_json::from_str(data)?;
115-
println!("Please call {} at the number {}", p.name, p.phones[0]);
116153
```
117154

118155
This is the same `serde_json::from_str` function as before, but this time we
119-
assign the return value to a variable of type `Person` so Serde JSON will
156+
assign the return value to a variable of type `Person` so Serde will
120157
automatically interpret the input data as a `Person` and produce informative
121158
error messages if the layout does not conform to what a `Person` is expected
122159
to look like.
@@ -133,7 +170,7 @@ autocomplete field names to prevent typos, which was impossible in the
133170
when we write `p.phones[0]`, then `p.phones` is guaranteed to be a
134171
`Vec<String>` so indexing into it makes sense and produces a `String`.
135172

136-
## Constructing JSON
173+
## Constructing JSON values
137174

138175
Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value`
139176
objects with very natural JSON syntax. In order to use this macro,
@@ -188,7 +225,7 @@ This is amazingly convenient but we have the problem we had before with
188225
wrong. Serde JSON provides a better way of serializing strongly-typed data
189226
structures into JSON text.
190227

191-
## Serializing data structures
228+
## Creating JSON by serializing data structures
192229

193230
A data structure can be converted to a JSON string by
194231
[`serde_json::to_string`][to_string]. There is also
@@ -197,18 +234,35 @@ A data structure can be converted to a JSON string by
197234
such as a File or a TCP stream.
198235

199236
```rust
237+
extern crate serde;
238+
extern crate serde_json;
239+
240+
#[macro_use]
241+
extern crate serde_derive;
242+
243+
use serde_json::Error;
244+
200245
#[derive(Serialize, Deserialize)]
201246
struct Address {
202247
street: String,
203248
city: String,
204249
}
205250

206-
let address = Address {
207-
street: "10 Downing Street".to_owned(),
208-
city: "London".to_owned(),
209-
};
251+
fn print_an_address() -> Result<(), Error> {
252+
// Some data structure.
253+
let address = Address {
254+
street: "10 Downing Street".to_owned(),
255+
city: "London".to_owned(),
256+
};
210257

211-
let j = serde_json::to_string(&address)?;
258+
// Serialize it to a JSON string.
259+
let j = serde_json::to_string(&address)?;
260+
261+
// Print, write to a file, or send to an HTTP server.
262+
println!("{}", j);
263+
264+
Ok(())
265+
}
212266
```
213267

214268
Any type that implements Serde's `Serialize` trait can be serialized this

json/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "serde_json"
3-
version = "0.9.9"
3+
version = "0.9.10"
44
authors = ["Erick Tryzelaar <[email protected]>"]
55
license = "MIT/Apache-2.0"
66
description = "A JSON serialization file format"

0 commit comments

Comments
 (0)