-
-
Notifications
You must be signed in to change notification settings - Fork 796
/
Copy pathjson.rs
3412 lines (3017 loc) · 112 KB
/
json.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Rust JSON serialization library
// Copyright (c) 2011 Google Inc.
#![forbid(non_camel_case_types)]
#![allow(missing_doc)]
/*!
JSON parsing and serialization
# What is JSON?
JSON (JavaScript Object Notation) is a way to write data in Javascript.
Like XML it allows one to encode structured data in a text format that can be read by humans easily.
Its native compatibility with JavaScript and its simple syntax make it used widely.
Json data are encoded in a form of "key":"value".
Data types that can be encoded are JavaScript types :
boolean (`true` or `false`), number (`f64`), string, array, object, null.
An object is a series of string keys mapping to values, in `"key": value` format.
Arrays are enclosed in square brackets ([ ... ]) and objects in curly brackets ({ ... }).
A simple JSON document encoding a person, his/her age, address and phone numbers could look like:
```ignore
{
"FirstName": "John",
"LastName": "Doe",
"Age": 43,
"Address": {
"Street": "Downing Street 10",
"City": "London",
"Country": "Great Britain"
},
"PhoneNumbers": [
"+44 1234567",
"+44 2345678"
]
}
```
# Rust Type-based Encoding and Decoding
Rust provides a mechanism for low boilerplate encoding & decoding
of values to and from JSON via the serialization API.
To be able to encode a piece of data, it must implement the `serialize::Encodable` trait.
To be able to decode a piece of data, it must implement the `serialize::Decodable` trait.
The Rust compiler provides an annotation to automatically generate
the code for these traits: `#[deriving(Decodable, Encodable)]`
To encode using Encodable :
```rust
use std::io;
use serialize::{json, Encodable};
#[deriving(Encodable)]
pub struct TestStruct {
data_str: ~str,
}
fn main() {
let to_encode_object = TestStruct{data_str:"example of string to encode".to_owned()};
let mut m = io::MemWriter::new();
{
let mut encoder = json::Encoder::new(&mut m as &mut std::io::Writer);
match to_encode_object.encode(&mut encoder) {
Ok(()) => (),
Err(e) => fail!("json encoding error: {}", e)
};
}
}
```
Two wrapper functions are provided to encode a Encodable object
into a string (~str) or buffer (~[u8]): `str_encode(&m)` and `buffer_encode(&m)`.
```rust
use serialize::json;
let to_encode_object = "example of string to encode".to_owned();
let encoded_str: ~str = json::Encoder::str_encode(&to_encode_object);
```
JSON API provide an enum `json::Json` and a trait `ToJson` to encode object.
The trait `ToJson` encode object into a container `json::Json` and the API provide writer
to encode them into a stream or a string ...
When using `ToJson` the `Encodable` trait implementation is not mandatory.
A basic `ToJson` example using a TreeMap of attribute name / attribute value:
```rust
extern crate collections;
extern crate serialize;
use serialize::json;
use serialize::json::ToJson;
use collections::TreeMap;
pub struct MyStruct {
attr1: u8,
attr2: ~str,
}
impl ToJson for MyStruct {
fn to_json( &self ) -> json::Json {
let mut d = box TreeMap::new();
d.insert("attr1".to_owned(), self.attr1.to_json());
d.insert("attr2".to_owned(), self.attr2.to_json());
json::Object(d)
}
}
fn main() {
let test2: MyStruct = MyStruct {attr1: 1, attr2:"test".to_owned()};
let tjson: json::Json = test2.to_json();
let json_str: ~str = tjson.to_str();
}
```
To decode a JSON string using `Decodable` trait :
```rust
extern crate serialize;
use serialize::{json, Decodable};
#[deriving(Decodable)]
pub struct MyStruct {
attr1: u8,
attr2: ~str,
}
fn main() {
let json_str_to_decode: ~str =
"{\"attr1\":1,\"attr2\":\"toto\"}".to_owned();
let json_object = json::from_str(json_str_to_decode);
let mut decoder = json::Decoder::new(json_object.unwrap());
let decoded_object: MyStruct = match Decodable::decode(&mut decoder) {
Ok(v) => v,
Err(e) => fail!("Decoding error: {}", e)
}; // create the final object
}
```
# Examples of use
## Using Autoserialization
Create a struct called TestStruct1 and serialize and deserialize it to and from JSON
using the serialization API, using the derived serialization code.
```rust
extern crate serialize;
use serialize::{json, Encodable, Decodable};
#[deriving(Decodable, Encodable)] //generate Decodable, Encodable impl.
pub struct TestStruct1 {
data_int: u8,
data_str: ~str,
data_vector: Vec<u8>,
}
// To serialize use the `json::str_encode` to encode an object in a string.
// It calls the generated `Encodable` impl.
fn main() {
let to_encode_object = TestStruct1
{data_int: 1, data_str:"toto".to_owned(), data_vector:vec![2,3,4,5]};
let encoded_str: ~str = json::Encoder::str_encode(&to_encode_object);
// To deserialize use the `json::from_str` and `json::Decoder`
let json_object = json::from_str(encoded_str);
let mut decoder = json::Decoder::new(json_object.unwrap());
let decoded1: TestStruct1 = Decodable::decode(&mut decoder).unwrap(); // create the final object
}
```
## Using `ToJson`
This example use the ToJson impl to deserialize the JSON string.
Example of `ToJson` trait implementation for TestStruct1.
```rust
extern crate serialize;
extern crate collections;
use serialize::json::ToJson;
use serialize::{json, Encodable, Decodable};
use collections::TreeMap;
#[deriving(Decodable, Encodable)] // generate Decodable, Encodable impl.
pub struct TestStruct1 {
data_int: u8,
data_str: ~str,
data_vector: Vec<u8>,
}
impl ToJson for TestStruct1 {
fn to_json( &self ) -> json::Json {
let mut d = box TreeMap::new();
d.insert("data_int".to_owned(), self.data_int.to_json());
d.insert("data_str".to_owned(), self.data_str.to_json());
d.insert("data_vector".to_owned(), self.data_vector.to_json());
json::Object(d)
}
}
fn main() {
// Serialization using our impl of to_json
let test2: TestStruct1 = TestStruct1 {data_int: 1, data_str:"toto".to_owned(),
data_vector:vec![2,3,4,5]};
let tjson: json::Json = test2.to_json();
let json_str: ~str = tjson.to_str();
// Deserialize like before.
let mut decoder = json::Decoder::new(json::from_str(json_str).unwrap());
// create the final object
let decoded2: TestStruct1 = Decodable::decode(&mut decoder).unwrap();
}
```
*/
use std::char;
use std::f64;
use std::fmt;
use std::io::MemWriter;
use std::io;
use std::mem::swap;
use std::num;
use std::str::ScalarValue;
use std::str;
use std::strbuf::StrBuf;
use std::vec::Vec;
use de;
use collections::{HashMap, TreeMap};
/// Represents a json value
#[deriving(Clone, Eq)]
pub enum Json {
Number(f64),
String(~str),
Boolean(bool),
List(List),
Object(Box<Object>),
Null,
}
pub type List = Vec<Json>;
pub type Object = TreeMap<~str, Json>;
/// The errors that can arise while parsing a JSON stream.
#[deriving(Clone, Eq)]
pub enum ErrorCode {
InvalidSyntax,
InvalidNumber,
EOFWhileParsingObject,
EOFWhileParsingList,
EOFWhileParsingValue,
EOFWhileParsingString,
KeyMustBeAString,
ExpectedColon,
TrailingCharacters,
InvalidEscape,
InvalidUnicodeCodePoint,
LoneLeadingSurrogateInHexEscape,
UnexpectedEndOfHexEscape,
UnrecognizedHex,
NotFourDigit,
NotUtf8,
}
#[deriving(Clone, Eq, Show)]
pub enum ParserError {
/// msg, line, col
SyntaxError(ErrorCode, uint, uint),
IoError(io::IoErrorKind, &'static str),
}
// Builder and Parser have the same errors.
pub type BuilderError = ParserError;
#[deriving(Clone, Eq, Show)]
pub enum DecoderError {
ParseError(ParserError),
ExpectedError(~str, ~str),
MissingFieldError(~str),
UnknownVariantError(~str),
}
/// Returns a readable error string for a given error code.
pub fn error_str(error: ErrorCode) -> &'static str {
return match error {
InvalidSyntax => "invalid syntax",
InvalidNumber => "invalid number",
EOFWhileParsingObject => "EOF While parsing object",
EOFWhileParsingList => "EOF While parsing list",
EOFWhileParsingValue => "EOF While parsing value",
EOFWhileParsingString => "EOF While parsing string",
KeyMustBeAString => "key must be a string",
ExpectedColon => "expected `:`",
TrailingCharacters => "trailing characters",
InvalidEscape => "invalid escape",
UnrecognizedHex => "invalid \\u escape (unrecognized hex)",
NotFourDigit => "invalid \\u escape (not four digits)",
NotUtf8 => "contents not utf-8",
InvalidUnicodeCodePoint => "invalid unicode code point",
LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
UnexpectedEndOfHexEscape => "unexpected end of hex escape",
}
}
impl fmt::Show for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
error_str(*self).fmt(f)
}
}
fn io_error_to_error(io: io::IoError) -> ParserError {
IoError(io.kind, io.desc)
}
pub type EncodeResult = io::IoResult<()>;
pub type DecodeResult<T> = Result<T, DecoderError>;
fn escape_str(s: &str) -> ~str {
let mut escaped = StrBuf::from_str("\"");
for c in s.chars() {
match c {
'"' => escaped.push_str("\\\""),
'\\' => escaped.push_str("\\\\"),
'\x08' => escaped.push_str("\\b"),
'\x0c' => escaped.push_str("\\f"),
'\n' => escaped.push_str("\\n"),
'\r' => escaped.push_str("\\r"),
'\t' => escaped.push_str("\\t"),
_ => escaped.push_char(c),
}
};
escaped.push_char('"');
escaped.into_owned()
}
fn spaces(n: uint) -> ~str {
let mut ss = StrBuf::new();
for _ in range(0, n) {
ss.push_str(" ");
}
return ss.into_owned();
}
/*
/// A structure for implementing serialization to JSON.
pub struct Encoder<'a> {
wr: &'a mut io::Writer,
}
impl<'a> Encoder<'a> {
/// Creates a new JSON encoder whose output will be written to the writer
/// specified.
pub fn new<'a>(wr: &'a mut io::Writer) -> Encoder<'a> {
Encoder { wr: wr }
}
/// Encode the specified struct into a json [u8]
pub fn buffer_encode<T:Encodable<Encoder<'a>, io::IoError>>(to_encode_object: &T) -> Vec<u8> {
//Serialize the object in a string using a writer
let mut m = MemWriter::new();
{
let mut encoder = Encoder::new(&mut m as &mut io::Writer);
// MemWriter never Errs
let _ = to_encode_object.encode(&mut encoder);
}
m.unwrap()
}
/// Encode the specified struct into a json str
pub fn str_encode<T:Encodable<Encoder<'a>, io::IoError>>(to_encode_object: &T) -> ~str {
let buff = Encoder::buffer_encode(to_encode_object);
str::from_utf8(buff.as_slice()).unwrap().to_owned()
}
}
impl<'a> ::Encoder<io::IoError> for Encoder<'a> {
fn emit_nil(&mut self) -> EncodeResult { write!(self.wr, "null") }
fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_u32(&mut self, v: u32) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_u16(&mut self, v: u16) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_u8(&mut self, v: u8) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_int(&mut self, v: int) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_i64(&mut self, v: i64) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_i32(&mut self, v: i32) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_i16(&mut self, v: i16) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_i8(&mut self, v: i8) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_bool(&mut self, v: bool) -> EncodeResult {
if v {
write!(self.wr, "true")
} else {
write!(self.wr, "false")
}
}
fn emit_f64(&mut self, v: f64) -> EncodeResult {
write!(self.wr, "{}", f64::to_str_digits(v, 6u))
}
fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_char(&mut self, v: char) -> EncodeResult { self.emit_str(str::from_char(v)) }
fn emit_str(&mut self, v: &str) -> EncodeResult {
write!(self.wr, "{}", escape_str(v))
}
fn emit_enum(&mut self,
_name: &str,
f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult { f(self) }
fn emit_enum_variant(&mut self,
name: &str,
_id: uint,
cnt: uint,
f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
// enums are encoded as strings or objects
// Bunny => "Bunny"
// Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
if cnt == 0 {
write!(self.wr, "{}", escape_str(name))
} else {
try!(write!(self.wr, "\\{\"variant\":"));
try!(write!(self.wr, "{}", escape_str(name)));
try!(write!(self.wr, ",\"fields\":["));
try!(f(self));
write!(self.wr, "]\\}")
}
}
fn emit_enum_variant_arg(&mut self,
idx: uint,
f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
if idx != 0 {
try!(write!(self.wr, ","));
}
f(self)
}
fn emit_enum_struct_variant(&mut self,
name: &str,
id: uint,
cnt: uint,
f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
self.emit_enum_variant(name, id, cnt, f)
}
fn emit_enum_struct_variant_field(&mut self,
_: &str,
idx: uint,
f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
self.emit_enum_variant_arg(idx, f)
}
fn emit_struct(&mut self,
_: &str,
_: uint,
f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
try!(write!(self.wr, r"\{"));
try!(f(self));
write!(self.wr, r"\}")
}
fn emit_struct_field(&mut self,
name: &str,
idx: uint,
f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
if idx != 0 { try!(write!(self.wr, ",")); }
try!(write!(self.wr, "{}:", escape_str(name)));
f(self)
}
fn emit_tuple(&mut self, len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
self.emit_seq(len, f)
}
fn emit_tuple_arg(&mut self,
idx: uint,
f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
self.emit_seq_elt(idx, f)
}
fn emit_tuple_struct(&mut self,
_name: &str,
len: uint,
f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
self.emit_seq(len, f)
}
fn emit_tuple_struct_arg(&mut self,
idx: uint,
f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
self.emit_seq_elt(idx, f)
}
fn emit_option(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
f(self)
}
fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
fn emit_option_some(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
f(self)
}
fn emit_seq(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
try!(write!(self.wr, "["));
try!(f(self));
write!(self.wr, "]")
}
fn emit_seq_elt(&mut self, idx: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
if idx != 0 {
try!(write!(self.wr, ","));
}
f(self)
}
fn emit_map(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
try!(write!(self.wr, r"\{"));
try!(f(self));
write!(self.wr, r"\}")
}
fn emit_map_elt_key(&mut self,
idx: uint,
f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
use std::str::from_utf8;
if idx != 0 { try!(write!(self.wr, ",")) }
// ref #12967, make sure to wrap a key in double quotes,
// in the event that its of a type that omits them (eg numbers)
let mut buf = MemWriter::new();
let mut check_encoder = Encoder::new(&mut buf);
try!(f(&mut check_encoder));
let buf = buf.unwrap();
let out = from_utf8(buf.as_slice()).unwrap();
let needs_wrapping = out.char_at(0) != '"' &&
out.char_at_reverse(out.len()) != '"';
if needs_wrapping { try!(write!(self.wr, "\"")); }
try!(f(self));
if needs_wrapping { try!(write!(self.wr, "\"")); }
Ok(())
}
fn emit_map_elt_val(&mut self,
_idx: uint,
f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
try!(write!(self.wr, ":"));
f(self)
}
}
/// Another encoder for JSON, but prints out human-readable JSON instead of
/// compact data
pub struct PrettyEncoder<'a> {
wr: &'a mut io::Writer,
indent: uint,
}
impl<'a> PrettyEncoder<'a> {
/// Creates a new encoder whose output will be written to the specified writer
pub fn new<'a>(wr: &'a mut io::Writer) -> PrettyEncoder<'a> {
PrettyEncoder {
wr: wr,
indent: 0,
}
}
}
impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> {
fn emit_nil(&mut self) -> EncodeResult { write!(self.wr, "null") }
fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_u32(&mut self, v: u32) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_u16(&mut self, v: u16) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_u8(&mut self, v: u8) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_int(&mut self, v: int) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_i64(&mut self, v: i64) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_i32(&mut self, v: i32) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_i16(&mut self, v: i16) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_i8(&mut self, v: i8) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_bool(&mut self, v: bool) -> EncodeResult {
if v {
write!(self.wr, "true")
} else {
write!(self.wr, "false")
}
}
fn emit_f64(&mut self, v: f64) -> EncodeResult {
write!(self.wr, "{}", f64::to_str_digits(v, 6u))
}
fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) }
fn emit_char(&mut self, v: char) -> EncodeResult { self.emit_str(str::from_char(v)) }
fn emit_str(&mut self, v: &str) -> EncodeResult {
write!(self.wr, "{}", escape_str(v))
}
fn emit_enum(&mut self,
_name: &str,
f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
f(self)
}
fn emit_enum_variant(&mut self,
name: &str,
_: uint,
cnt: uint,
f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
if cnt == 0 {
write!(self.wr, "{}", escape_str(name))
} else {
self.indent += 2;
try!(write!(self.wr, "[\n{}{},\n", spaces(self.indent),
escape_str(name)));
try!(f(self));
self.indent -= 2;
write!(self.wr, "\n{}]", spaces(self.indent))
}
}
fn emit_enum_variant_arg(&mut self,
idx: uint,
f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
if idx != 0 {
try!(write!(self.wr, ",\n"));
}
try!(write!(self.wr, "{}", spaces(self.indent)));
f(self)
}
fn emit_enum_struct_variant(&mut self,
name: &str,
id: uint,
cnt: uint,
f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
self.emit_enum_variant(name, id, cnt, f)
}
fn emit_enum_struct_variant_field(&mut self,
_: &str,
idx: uint,
f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
self.emit_enum_variant_arg(idx, f)
}
fn emit_struct(&mut self,
_: &str,
len: uint,
f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
if len == 0 {
write!(self.wr, "\\{\\}")
} else {
try!(write!(self.wr, "\\{"));
self.indent += 2;
try!(f(self));
self.indent -= 2;
write!(self.wr, "\n{}\\}", spaces(self.indent))
}
}
fn emit_struct_field(&mut self,
name: &str,
idx: uint,
f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
if idx == 0 {
try!(write!(self.wr, "\n"));
} else {
try!(write!(self.wr, ",\n"));
}
try!(write!(self.wr, "{}{}: ", spaces(self.indent), escape_str(name)));
f(self)
}
fn emit_tuple(&mut self,
len: uint,
f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
self.emit_seq(len, f)
}
fn emit_tuple_arg(&mut self,
idx: uint,
f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
self.emit_seq_elt(idx, f)
}
fn emit_tuple_struct(&mut self,
_: &str,
len: uint,
f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
self.emit_seq(len, f)
}
fn emit_tuple_struct_arg(&mut self,
idx: uint,
f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
self.emit_seq_elt(idx, f)
}
fn emit_option(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
f(self)
}
fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
fn emit_option_some(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
f(self)
}
fn emit_seq(&mut self,
len: uint,
f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
if len == 0 {
write!(self.wr, "[]")
} else {
try!(write!(self.wr, "["));
self.indent += 2;
try!(f(self));
self.indent -= 2;
write!(self.wr, "\n{}]", spaces(self.indent))
}
}
fn emit_seq_elt(&mut self,
idx: uint,
f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
if idx == 0 {
try!(write!(self.wr, "\n"));
} else {
try!(write!(self.wr, ",\n"));
}
try!(write!(self.wr, "{}", spaces(self.indent)));
f(self)
}
fn emit_map(&mut self,
len: uint,
f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
if len == 0 {
write!(self.wr, "\\{\\}")
} else {
try!(write!(self.wr, "\\{"));
self.indent += 2;
try!(f(self));
self.indent -= 2;
write!(self.wr, "\n{}\\}", spaces(self.indent))
}
}
fn emit_map_elt_key(&mut self,
idx: uint,
f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
use std::str::from_utf8;
if idx == 0 {
try!(write!(self.wr, "\n"));
} else {
try!(write!(self.wr, ",\n"));
}
try!(write!(self.wr, "{}", spaces(self.indent)));
// ref #12967, make sure to wrap a key in double quotes,
// in the event that its of a type that omits them (eg numbers)
let mut buf = MemWriter::new();
let mut check_encoder = PrettyEncoder::new(&mut buf);
try!(f(&mut check_encoder));
let buf = buf.unwrap();
let out = from_utf8(buf.as_slice()).unwrap();
let needs_wrapping = out.char_at(0) != '"' &&
out.char_at_reverse(out.len()) != '"';
if needs_wrapping { try!(write!(self.wr, "\"")); }
try!(f(self));
if needs_wrapping { try!(write!(self.wr, "\"")); }
Ok(())
}
fn emit_map_elt_val(&mut self,
_idx: uint,
f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
try!(write!(self.wr, ": "));
f(self)
}
}
impl<E: ::Encoder<S>, S> Encodable<E, S> for Json {
fn encode(&self, e: &mut E) -> Result<(), S> {
match *self {
Number(v) => v.encode(e),
String(ref v) => v.encode(e),
Boolean(v) => v.encode(e),
List(ref v) => v.encode(e),
Object(ref v) => v.encode(e),
Null => e.emit_nil(),
}
}
}
impl Json {
/// Encodes a json value into an io::writer. Uses a single line.
pub fn to_writer(&self, wr: &mut io::Writer) -> EncodeResult {
let mut encoder = Encoder::new(wr);
self.encode(&mut encoder)
}
/// Encodes a json value into an io::writer.
/// Pretty-prints in a more readable format.
pub fn to_pretty_writer(&self, wr: &mut io::Writer) -> EncodeResult {
let mut encoder = PrettyEncoder::new(wr);
self.encode(&mut encoder)
}
/// Encodes a json value into a string
pub fn to_pretty_str(&self) -> ~str {
let mut s = MemWriter::new();
self.to_pretty_writer(&mut s as &mut io::Writer).unwrap();
str::from_utf8(s.unwrap().as_slice()).unwrap().to_owned()
}
/// If the Json value is an Object, returns the value associated with the provided key.
/// Otherwise, returns None.
pub fn find<'a>(&'a self, key: &~str) -> Option<&'a Json>{
match self {
&Object(ref map) => map.find(key),
_ => None
}
}
/// Attempts to get a nested Json Object for each key in `keys`.
/// If any key is found not to exist, find_path will return None.
/// Otherwise, it will return the Json value associated with the final key.
pub fn find_path<'a>(&'a self, keys: &[&~str]) -> Option<&'a Json>{
let mut target = self;
for key in keys.iter() {
match target.find(*key) {
Some(t) => { target = t; },
None => return None
}
}
Some(target)
}
/// If the Json value is an Object, performs a depth-first search until
/// a value associated with the provided key is found. If no value is found
/// or the Json value is not an Object, returns None.
pub fn search<'a>(&'a self, key: &~str) -> Option<&'a Json> {
match self {
&Object(ref map) => {
match map.find(key) {
Some(json_value) => Some(json_value),
None => {
let mut value : Option<&'a Json> = None;
for (_, v) in map.iter() {
value = v.search(key);
if value.is_some() {
break;
}
}
value
}
}
},
_ => None
}
}
/// Returns true if the Json value is an Object. Returns false otherwise.
pub fn is_object<'a>(&'a self) -> bool {
self.as_object().is_some()
}
/// If the Json value is an Object, returns the associated TreeMap.
/// Returns None otherwise.
pub fn as_object<'a>(&'a self) -> Option<&'a Object> {
match self {
&Object(ref map) => Some(&**map),
_ => None
}
}
/// Returns true if the Json value is a List. Returns false otherwise.
pub fn is_list<'a>(&'a self) -> bool {
self.as_list().is_some()
}
/// If the Json value is a List, returns the associated vector.
/// Returns None otherwise.
pub fn as_list<'a>(&'a self) -> Option<&'a List> {
match self {
&List(ref list) => Some(&*list),
_ => None
}
}
/// Returns true if the Json value is a String. Returns false otherwise.
pub fn is_string<'a>(&'a self) -> bool {
self.as_string().is_some()
}
/// If the Json value is a String, returns the associated str.
/// Returns None otherwise.
pub fn as_string<'a>(&'a self) -> Option<&'a str> {
match *self {
String(ref s) => Some(s.as_slice()),
_ => None
}
}
/// Returns true if the Json value is a Number. Returns false otherwise.
pub fn is_number(&self) -> bool {
self.as_number().is_some()
}
/// If the Json value is a Number, returns the associated f64.
/// Returns None otherwise.
pub fn as_number(&self) -> Option<f64> {
match self {
&Number(n) => Some(n),
_ => None
}
}
/// Returns true if the Json value is a Boolean. Returns false otherwise.
pub fn is_boolean(&self) -> bool {
self.as_boolean().is_some()
}
/// If the Json value is a Boolean, returns the associated bool.
/// Returns None otherwise.
pub fn as_boolean(&self) -> Option<bool> {
match self {
&Boolean(b) => Some(b),
_ => None
}
}
/// Returns true if the Json value is a Null. Returns false otherwise.
pub fn is_null(&self) -> bool {
self.as_null().is_some()
}
/// If the Json value is a Null, returns ().
/// Returns None otherwise.
pub fn as_null(&self) -> Option<()> {
match self {
&Null => Some(()),
_ => None
}
}
}
*/
/// The output of the streaming parser.
#[deriving(Eq, Clone, Show)]
pub enum JsonEvent {
ObjectStart,
ObjectEnd,
ListStart,
ListEnd,
BooleanValue(bool),
NumberValue(f64),
StringValue(~str),
NullValue,
Error(ParserError),
}
#[deriving(Eq, Show)]
enum ParserState {
// Parse a value in a list, true means first element.
ParseList(bool),
// Parse ',' or ']' after an element in a list.
ParseListComma,
// Parse a key:value in an object, true means first element.
ParseObject(bool),
// Parse ',' or ']' after an element in an object.
ParseObjectComma,
// Initialial state.
ParseStart,
// Expecting the stream to end.
ParseBeforeFinish,
// Parsing can't continue.
ParseFinished,
}