@@ -44,15 +44,15 @@ with JSON data in Rust.
44
44
- ** As an untyped or loosely typed representation.** Maybe you want to
45
45
check that some JSON data is valid before passing it on, but without
46
46
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 .
48
48
- ** As a strongly typed Rust data structure.** When you expect all or most
49
49
of your data to conform to a particular structure and want to get real
50
50
work done without JSON's loosey-goosey nature tripping you up.
51
51
52
52
Serde JSON provides efficient, flexible, safe ways of converting data
53
53
between each of these representations.
54
54
55
- ## JSON to the Value enum
55
+ ## Operating on untyped JSON values
56
56
57
57
Any valid JSON data can be manipulated in the following recursive enum
58
58
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
76
76
a TCP stream.
77
77
78
78
``` 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
+ }" # ;
80
93
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
+ }
84
102
```
85
103
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.
92
110
93
- ## JSON to strongly typed data structures
111
+ ## Parsing JSON as strongly typed data structures
94
112
95
113
Serde provides a powerful way of mapping JSON data into Rust data structures
96
114
largely automatically.
97
115
98
116
``` 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
+
99
125
#[derive(Serialize , Deserialize )]
100
126
struct Person {
101
127
name : String ,
102
128
age : u8 ,
103
- address : Address ,
104
129
phones : Vec <String >,
105
130
}
106
131
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 (())
111
152
}
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 ]);
116
153
```
117
154
118
155
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
120
157
automatically interpret the input data as a ` Person ` and produce informative
121
158
error messages if the layout does not conform to what a ` Person ` is expected
122
159
to look like.
@@ -133,7 +170,7 @@ autocomplete field names to prevent typos, which was impossible in the
133
170
when we write ` p.phones[0] ` , then ` p.phones ` is guaranteed to be a
134
171
` Vec<String> ` so indexing into it makes sense and produces a ` String ` .
135
172
136
- ## Constructing JSON
173
+ ## Constructing JSON values
137
174
138
175
Serde JSON provides a [ ` json! ` macro] [ macro ] to build ` serde_json::Value `
139
176
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
188
225
wrong. Serde JSON provides a better way of serializing strongly-typed data
189
226
structures into JSON text.
190
227
191
- ## Serializing data structures
228
+ ## Creating JSON by serializing data structures
192
229
193
230
A data structure can be converted to a JSON string by
194
231
[ ` serde_json::to_string ` ] [ to_string ] . There is also
@@ -197,18 +234,35 @@ A data structure can be converted to a JSON string by
197
234
such as a File or a TCP stream.
198
235
199
236
``` 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
+
200
245
#[derive(Serialize , Deserialize )]
201
246
struct Address {
202
247
street : String ,
203
248
city : String ,
204
249
}
205
250
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
+ };
210
257
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
+ }
212
266
```
213
267
214
268
Any type that implements Serde's ` Serialize ` trait can be serialized this
0 commit comments