1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Rust JSON serialization library
12 // Copyright (c) 2011 Google Inc.
14 #![forbid(non_camel_case_types)]
15 #![allow(missing_doc)]
18 JSON parsing and serialization
22 JSON (JavaScript Object Notation) is a way to write data in Javascript.
23 Like XML it allows one to encode structured data in a text format that can be read by humans easily.
24 Its native compatibility with JavaScript and its simple syntax make it used widely.
26 Json data are encoded in a form of "key":"value".
27 Data types that can be encoded are JavaScript types :
28 boolean (`true` or `false`), number (`f64`), string, array, object, null.
29 An object is a series of string keys mapping to values, in `"key": value` format.
30 Arrays are enclosed in square brackets ([ ... ]) and objects in curly brackets ({ ... }).
31 A simple JSON document encoding a person, his/her age, address and phone numbers could look like:
39 "Street": "Downing Street 10",
41 "Country": "Great Britain"
50 # Rust Type-based Encoding and Decoding
52 Rust provides a mechanism for low boilerplate encoding & decoding
53 of values to and from JSON via the serialization API.
54 To be able to encode a piece of data, it must implement the `serialize::Encodable` trait.
55 To be able to decode a piece of data, it must implement the `serialize::Decodable` trait.
56 The Rust compiler provides an annotation to automatically generate
57 the code for these traits: `#[deriving(Decodable, Encodable)]`
59 To encode using Encodable :
63 use serialize::{json, Encodable};
65 #[deriving(Encodable)]
66 pub struct TestStruct {
71 let to_encode_object = TestStruct{data_str:~"example of string to encode"};
72 let mut m = io::MemWriter::new();
74 let mut encoder = json::Encoder::new(&mut m as &mut std::io::Writer);
75 match to_encode_object.encode(&mut encoder) {
77 Err(e) => fail!("json encoding error: {}", e)
83 Two wrapper functions are provided to encode a Encodable object
84 into a string (~str) or buffer (~[u8]): `str_encode(&m)` and `buffer_encode(&m)`.
88 let to_encode_object = ~"example of string to encode";
89 let encoded_str: ~str = json::Encoder::str_encode(&to_encode_object);
92 JSON API provide an enum `json::Json` and a trait `ToJson` to encode object.
93 The trait `ToJson` encode object into a container `json::Json` and the API provide writer
94 to encode them into a stream or a string ...
96 When using `ToJson` the `Encodable` trait implementation is not mandatory.
98 A basic `ToJson` example using a TreeMap of attribute name / attribute value:
102 extern crate collections;
103 extern crate serialize;
106 use serialize::json::ToJson;
107 use collections::TreeMap;
109 pub struct MyStruct {
114 impl ToJson for MyStruct {
115 fn to_json( &self ) -> json::Json {
116 let mut d = ~TreeMap::new();
117 d.insert(~"attr1", self.attr1.to_json());
118 d.insert(~"attr2", self.attr2.to_json());
124 let test2: MyStruct = MyStruct {attr1: 1, attr2:~"test"};
125 let tjson: json::Json = test2.to_json();
126 let json_str: ~str = tjson.to_str();
130 To decode a JSON string using `Decodable` trait :
133 extern crate serialize;
134 use serialize::{json, Decodable};
136 #[deriving(Decodable)]
137 pub struct MyStruct {
143 let json_str_to_decode: ~str =
144 ~"{\"attr1\":1,\"attr2\":\"toto\"}";
145 let json_object = json::from_str(json_str_to_decode);
146 let mut decoder = json::Decoder::new(json_object.unwrap());
147 let decoded_object: MyStruct = match Decodable::decode(&mut decoder) {
149 Err(e) => fail!("Decoding error: {}", e)
150 }; // create the final object
156 ## Using Autoserialization
158 Create a struct called TestStruct1 and serialize and deserialize it to and from JSON
159 using the serialization API, using the derived serialization code.
162 extern crate serialize;
163 use serialize::{json, Encodable, Decodable};
165 #[deriving(Decodable, Encodable)] //generate Decodable, Encodable impl.
166 pub struct TestStruct1 {
172 // To serialize use the `json::str_encode` to encode an object in a string.
173 // It calls the generated `Encodable` impl.
175 let to_encode_object = TestStruct1
176 {data_int: 1, data_str:~"toto", data_vector:~[2,3,4,5]};
177 let encoded_str: ~str = json::Encoder::str_encode(&to_encode_object);
179 // To deserialize use the `json::from_str` and `json::Decoder`
181 let json_object = json::from_str(encoded_str);
182 let mut decoder = json::Decoder::new(json_object.unwrap());
183 let decoded1: TestStruct1 = Decodable::decode(&mut decoder).unwrap(); // create the final object
189 This example use the ToJson impl to deserialize the JSON string.
190 Example of `ToJson` trait implementation for TestStruct1.
193 extern crate serialize;
194 extern crate collections;
196 use serialize::json::ToJson;
197 use serialize::{json, Encodable, Decodable};
198 use collections::TreeMap;
200 #[deriving(Decodable, Encodable)] // generate Decodable, Encodable impl.
201 pub struct TestStruct1 {
207 impl ToJson for TestStruct1 {
208 fn to_json( &self ) -> json::Json {
209 let mut d = ~TreeMap::new();
210 d.insert(~"data_int", self.data_int.to_json());
211 d.insert(~"data_str", self.data_str.to_json());
212 d.insert(~"data_vector", self.data_vector.to_json());
218 // Serialization using our impl of to_json
220 let test2: TestStruct1 = TestStruct1 {data_int: 1, data_str:~"toto", data_vector:~[2,3,4,5]};
221 let tjson: json::Json = test2.to_json();
222 let json_str: ~str = tjson.to_str();
224 // Deserialize like before.
226 let mut decoder = json::Decoder::new(json::from_str(json_str).unwrap());
227 // create the final object
228 let decoded2: TestStruct1 = Decodable::decode(&mut decoder).unwrap();
234 use collections::HashMap;
238 use std::io::MemWriter;
242 use std::str::ScalarValue;
243 use std::strbuf::StrBuf;
246 use collections::TreeMap;
248 /// Represents a json value
249 #[deriving(Clone, Eq)]
259 pub type List = ~[Json];
260 pub type Object = TreeMap<~str, Json>;
262 #[deriving(Eq, Show)]
265 ParseError(~str, uint, uint),
266 ExpectedError(~str, ~str),
267 MissingFieldError(~str),
268 UnknownVariantError(~str),
272 pub type EncodeResult = io::IoResult<()>;
273 pub type DecodeResult<T> = Result<T, Error>;
275 fn escape_str(s: &str) -> ~str {
276 let mut escaped = StrBuf::from_str("\"");
279 '"' => escaped.push_str("\\\""),
280 '\\' => escaped.push_str("\\\\"),
281 '\x08' => escaped.push_str("\\b"),
282 '\x0c' => escaped.push_str("\\f"),
283 '\n' => escaped.push_str("\\n"),
284 '\r' => escaped.push_str("\\r"),
285 '\t' => escaped.push_str("\\t"),
286 _ => escaped.push_char(c),
289 escaped.push_char('"');
293 fn spaces(n: uint) -> ~str {
294 let mut ss = StrBuf::new();
295 for _ in range(0, n) {
298 return ss.into_owned();
301 /// A structure for implementing serialization to JSON.
302 pub struct Encoder<'a> {
303 wr: &'a mut io::Writer,
306 impl<'a> Encoder<'a> {
307 /// Creates a new JSON encoder whose output will be written to the writer
309 pub fn new<'a>(wr: &'a mut io::Writer) -> Encoder<'a> {
313 /// Encode the specified struct into a json [u8]
314 pub fn buffer_encode<T:Encodable<Encoder<'a>, io::IoError>>(to_encode_object: &T) -> Vec<u8> {
315 //Serialize the object in a string using a writer
316 let mut m = MemWriter::new();
318 let mut encoder = Encoder::new(&mut m as &mut io::Writer);
319 // MemWriter never Errs
320 let _ = to_encode_object.encode(&mut encoder);
325 /// Encode the specified struct into a json str
326 pub fn str_encode<T:Encodable<Encoder<'a>, io::IoError>>(to_encode_object: &T) -> ~str {
327 let buff = Encoder::buffer_encode(to_encode_object);
328 str::from_utf8(buff.as_slice()).unwrap().to_owned()
332 impl<'a> ::Encoder<io::IoError> for Encoder<'a> {
333 fn emit_nil(&mut self) -> EncodeResult { write!(self.wr, "null") }
335 fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) }
336 fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) }
337 fn emit_u32(&mut self, v: u32) -> EncodeResult { self.emit_f64(v as f64) }
338 fn emit_u16(&mut self, v: u16) -> EncodeResult { self.emit_f64(v as f64) }
339 fn emit_u8(&mut self, v: u8) -> EncodeResult { self.emit_f64(v as f64) }
341 fn emit_int(&mut self, v: int) -> EncodeResult { self.emit_f64(v as f64) }
342 fn emit_i64(&mut self, v: i64) -> EncodeResult { self.emit_f64(v as f64) }
343 fn emit_i32(&mut self, v: i32) -> EncodeResult { self.emit_f64(v as f64) }
344 fn emit_i16(&mut self, v: i16) -> EncodeResult { self.emit_f64(v as f64) }
345 fn emit_i8(&mut self, v: i8) -> EncodeResult { self.emit_f64(v as f64) }
347 fn emit_bool(&mut self, v: bool) -> EncodeResult {
349 write!(self.wr, "true")
351 write!(self.wr, "false")
355 fn emit_f64(&mut self, v: f64) -> EncodeResult {
356 write!(self.wr, "{}", f64::to_str_digits(v, 6u))
358 fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) }
360 fn emit_char(&mut self, v: char) -> EncodeResult { self.emit_str(str::from_char(v)) }
361 fn emit_str(&mut self, v: &str) -> EncodeResult {
362 write!(self.wr, "{}", escape_str(v))
365 fn emit_enum(&mut self,
367 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult { f(self) }
369 fn emit_enum_variant(&mut self,
373 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
374 // enums are encoded as strings or objects
376 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
378 write!(self.wr, "{}", escape_str(name))
380 try!(write!(self.wr, "\\{\"variant\":"));
381 try!(write!(self.wr, "{}", escape_str(name)));
382 try!(write!(self.wr, ",\"fields\":["));
384 write!(self.wr, "]\\}")
388 fn emit_enum_variant_arg(&mut self,
390 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
392 try!(write!(self.wr, ","));
397 fn emit_enum_struct_variant(&mut self,
401 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
402 self.emit_enum_variant(name, id, cnt, f)
405 fn emit_enum_struct_variant_field(&mut self,
408 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
409 self.emit_enum_variant_arg(idx, f)
412 fn emit_struct(&mut self,
415 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
416 try!(write!(self.wr, r"\{"));
418 write!(self.wr, r"\}")
421 fn emit_struct_field(&mut self,
424 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
425 if idx != 0 { try!(write!(self.wr, ",")); }
426 try!(write!(self.wr, "{}:", escape_str(name)));
430 fn emit_tuple(&mut self, len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
431 self.emit_seq(len, f)
433 fn emit_tuple_arg(&mut self,
435 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
436 self.emit_seq_elt(idx, f)
439 fn emit_tuple_struct(&mut self,
442 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
443 self.emit_seq(len, f)
445 fn emit_tuple_struct_arg(&mut self,
447 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
448 self.emit_seq_elt(idx, f)
451 fn emit_option(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
454 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
455 fn emit_option_some(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
459 fn emit_seq(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
460 try!(write!(self.wr, "["));
465 fn emit_seq_elt(&mut self, idx: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
467 try!(write!(self.wr, ","));
472 fn emit_map(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
473 try!(write!(self.wr, r"\{"));
475 write!(self.wr, r"\}")
478 fn emit_map_elt_key(&mut self,
480 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
481 use std::str::from_utf8;
482 if idx != 0 { try!(write!(self.wr, ",")) }
483 // ref #12967, make sure to wrap a key in double quotes,
484 // in the event that its of a type that omits them (eg numbers)
485 let mut buf = MemWriter::new();
486 let mut check_encoder = Encoder::new(&mut buf);
487 try!(f(&mut check_encoder));
488 let buf = buf.unwrap();
489 let out = from_utf8(buf.as_slice()).unwrap();
490 let needs_wrapping = out.char_at(0) != '"' &&
491 out.char_at_reverse(out.len()) != '"';
492 if needs_wrapping { try!(write!(self.wr, "\"")); }
494 if needs_wrapping { try!(write!(self.wr, "\"")); }
498 fn emit_map_elt_val(&mut self,
500 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
501 try!(write!(self.wr, ":"));
506 /// Another encoder for JSON, but prints out human-readable JSON instead of
508 pub struct PrettyEncoder<'a> {
509 wr: &'a mut io::Writer,
513 impl<'a> PrettyEncoder<'a> {
514 /// Creates a new encoder whose output will be written to the specified writer
515 pub fn new<'a>(wr: &'a mut io::Writer) -> PrettyEncoder<'a> {
523 impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> {
524 fn emit_nil(&mut self) -> EncodeResult { write!(self.wr, "null") }
526 fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) }
527 fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) }
528 fn emit_u32(&mut self, v: u32) -> EncodeResult { self.emit_f64(v as f64) }
529 fn emit_u16(&mut self, v: u16) -> EncodeResult { self.emit_f64(v as f64) }
530 fn emit_u8(&mut self, v: u8) -> EncodeResult { self.emit_f64(v as f64) }
532 fn emit_int(&mut self, v: int) -> EncodeResult { self.emit_f64(v as f64) }
533 fn emit_i64(&mut self, v: i64) -> EncodeResult { self.emit_f64(v as f64) }
534 fn emit_i32(&mut self, v: i32) -> EncodeResult { self.emit_f64(v as f64) }
535 fn emit_i16(&mut self, v: i16) -> EncodeResult { self.emit_f64(v as f64) }
536 fn emit_i8(&mut self, v: i8) -> EncodeResult { self.emit_f64(v as f64) }
538 fn emit_bool(&mut self, v: bool) -> EncodeResult {
540 write!(self.wr, "true")
542 write!(self.wr, "false")
546 fn emit_f64(&mut self, v: f64) -> EncodeResult {
547 write!(self.wr, "{}", f64::to_str_digits(v, 6u))
549 fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) }
551 fn emit_char(&mut self, v: char) -> EncodeResult { self.emit_str(str::from_char(v)) }
552 fn emit_str(&mut self, v: &str) -> EncodeResult {
553 write!(self.wr, "{}", escape_str(v))
556 fn emit_enum(&mut self,
558 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
562 fn emit_enum_variant(&mut self,
566 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
568 write!(self.wr, "{}", escape_str(name))
571 try!(write!(self.wr, "[\n{}{},\n", spaces(self.indent),
575 write!(self.wr, "\n{}]", spaces(self.indent))
579 fn emit_enum_variant_arg(&mut self,
581 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
583 try!(write!(self.wr, ",\n"));
585 try!(write!(self.wr, "{}", spaces(self.indent)));
589 fn emit_enum_struct_variant(&mut self,
593 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
594 self.emit_enum_variant(name, id, cnt, f)
597 fn emit_enum_struct_variant_field(&mut self,
600 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
601 self.emit_enum_variant_arg(idx, f)
605 fn emit_struct(&mut self,
608 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
610 write!(self.wr, "\\{\\}")
612 try!(write!(self.wr, "\\{"));
616 write!(self.wr, "\n{}\\}", spaces(self.indent))
620 fn emit_struct_field(&mut self,
623 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
625 try!(write!(self.wr, "\n"));
627 try!(write!(self.wr, ",\n"));
629 try!(write!(self.wr, "{}{}: ", spaces(self.indent), escape_str(name)));
633 fn emit_tuple(&mut self,
635 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
636 self.emit_seq(len, f)
638 fn emit_tuple_arg(&mut self,
640 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
641 self.emit_seq_elt(idx, f)
644 fn emit_tuple_struct(&mut self,
647 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
648 self.emit_seq(len, f)
650 fn emit_tuple_struct_arg(&mut self,
652 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
653 self.emit_seq_elt(idx, f)
656 fn emit_option(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
659 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
660 fn emit_option_some(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
664 fn emit_seq(&mut self,
666 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
668 write!(self.wr, "[]")
670 try!(write!(self.wr, "["));
674 write!(self.wr, "\n{}]", spaces(self.indent))
678 fn emit_seq_elt(&mut self,
680 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
682 try!(write!(self.wr, "\n"));
684 try!(write!(self.wr, ",\n"));
686 try!(write!(self.wr, "{}", spaces(self.indent)));
690 fn emit_map(&mut self,
692 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
694 write!(self.wr, "\\{\\}")
696 try!(write!(self.wr, "\\{"));
700 write!(self.wr, "\n{}\\}", spaces(self.indent))
704 fn emit_map_elt_key(&mut self,
706 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
707 use std::str::from_utf8;
709 try!(write!(self.wr, "\n"));
711 try!(write!(self.wr, ",\n"));
713 try!(write!(self.wr, "{}", spaces(self.indent)));
714 // ref #12967, make sure to wrap a key in double quotes,
715 // in the event that its of a type that omits them (eg numbers)
716 let mut buf = MemWriter::new();
717 let mut check_encoder = PrettyEncoder::new(&mut buf);
718 try!(f(&mut check_encoder));
719 let buf = buf.unwrap();
720 let out = from_utf8(buf.as_slice()).unwrap();
721 let needs_wrapping = out.char_at(0) != '"' &&
722 out.char_at_reverse(out.len()) != '"';
723 if needs_wrapping { try!(write!(self.wr, "\"")); }
725 if needs_wrapping { try!(write!(self.wr, "\"")); }
729 fn emit_map_elt_val(&mut self,
731 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
732 try!(write!(self.wr, ": "));
737 impl<E: ::Encoder<S>, S> Encodable<E, S> for Json {
738 fn encode(&self, e: &mut E) -> Result<(), S> {
740 Number(v) => v.encode(e),
741 String(ref v) => v.encode(e),
742 Boolean(v) => v.encode(e),
743 List(ref v) => v.encode(e),
744 Object(ref v) => v.encode(e),
745 Null => e.emit_nil(),
751 /// Encodes a json value into a io::writer. Uses a single line.
752 pub fn to_writer(&self, wr: &mut io::Writer) -> EncodeResult {
753 let mut encoder = Encoder::new(wr);
754 self.encode(&mut encoder)
757 /// Encodes a json value into a io::writer.
758 /// Pretty-prints in a more readable format.
759 pub fn to_pretty_writer(&self, wr: &mut io::Writer) -> EncodeResult {
760 let mut encoder = PrettyEncoder::new(wr);
761 self.encode(&mut encoder)
764 /// Encodes a json value into a string
765 pub fn to_pretty_str(&self) -> ~str {
766 let mut s = MemWriter::new();
767 self.to_pretty_writer(&mut s as &mut io::Writer).unwrap();
768 str::from_utf8(s.unwrap().as_slice()).unwrap().to_owned()
771 /// If the Json value is an Object, returns the value associated with the provided key.
772 /// Otherwise, returns None.
773 pub fn find<'a>(&'a self, key: &~str) -> Option<&'a Json>{
775 &Object(ref map) => map.find(key),
780 /// Attempts to get a nested Json Object for each key in `keys`.
781 /// If any key is found not to exist, find_path will return None.
782 /// Otherwise, it will return the Json value associated with the final key.
783 pub fn find_path<'a>(&'a self, keys: &[&~str]) -> Option<&'a Json>{
784 let mut target = self;
785 for key in keys.iter() {
786 match target.find(*key) {
787 Some(t) => { target = t; },
794 /// If the Json value is an Object, performs a depth-first search until
795 /// a value associated with the provided key is found. If no value is found
796 /// or the Json value is not an Object, returns None.
797 pub fn search<'a>(&'a self, key: &~str) -> Option<&'a Json> {
799 &Object(ref map) => {
800 match map.find(key) {
801 Some(json_value) => Some(json_value),
803 let mut value : Option<&'a Json> = None;
804 for (_, v) in map.iter() {
805 value = v.search(key);
818 /// Returns true if the Json value is an Object. Returns false otherwise.
819 pub fn is_object<'a>(&'a self) -> bool {
820 self.as_object().is_some()
823 /// If the Json value is an Object, returns the associated TreeMap.
824 /// Returns None otherwise.
825 pub fn as_object<'a>(&'a self) -> Option<&'a Object> {
827 &Object(ref map) => Some(&**map),
832 /// Returns true if the Json value is a List. Returns false otherwise.
833 pub fn is_list<'a>(&'a self) -> bool {
834 self.as_list().is_some()
837 /// If the Json value is a List, returns the associated vector.
838 /// Returns None otherwise.
839 pub fn as_list<'a>(&'a self) -> Option<&'a List> {
841 &List(ref list) => Some(&*list),
846 /// Returns true if the Json value is a String. Returns false otherwise.
847 pub fn is_string<'a>(&'a self) -> bool {
848 self.as_string().is_some()
851 /// If the Json value is a String, returns the associated str.
852 /// Returns None otherwise.
853 pub fn as_string<'a>(&'a self) -> Option<&'a str> {
855 String(ref s) => Some(s.as_slice()),
860 /// Returns true if the Json value is a Number. Returns false otherwise.
861 pub fn is_number(&self) -> bool {
862 self.as_number().is_some()
865 /// If the Json value is a Number, returns the associated f64.
866 /// Returns None otherwise.
867 pub fn as_number(&self) -> Option<f64> {
869 &Number(n) => Some(n),
874 /// Returns true if the Json value is a Boolean. Returns false otherwise.
875 pub fn is_boolean(&self) -> bool {
876 self.as_boolean().is_some()
879 /// If the Json value is a Boolean, returns the associated bool.
880 /// Returns None otherwise.
881 pub fn as_boolean(&self) -> Option<bool> {
883 &Boolean(b) => Some(b),
888 /// Returns true if the Json value is a Null. Returns false otherwise.
889 pub fn is_null(&self) -> bool {
890 self.as_null().is_some()
893 /// If the Json value is a Null, returns ().
894 /// Returns None otherwise.
895 pub fn as_null(&self) -> Option<()> {
903 pub struct Parser<T> {
910 impl<T: Iterator<char>> Parser<T> {
911 /// Decode a json value from an Iterator<char>
912 pub fn new(rdr: T) -> Parser<T> {
924 impl<T: Iterator<char>> Parser<T> {
925 pub fn parse(&mut self) -> DecodeResult<Json> {
926 match self.parse_value() {
928 // Skip trailing whitespaces.
929 self.parse_whitespace();
930 // Make sure there is no trailing characters.
934 self.error(~"trailing characters")
942 impl<T : Iterator<char>> Parser<T> {
943 fn eof(&self) -> bool { self.ch.is_none() }
944 fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
946 self.ch = self.rdr.next();
948 if self.ch_is('\n') {
956 fn next_char(&mut self) -> Option<char> {
960 fn ch_is(&self, c: char) -> bool {
964 fn error<T>(&self, msg: ~str) -> DecodeResult<T> {
965 Err(ParseError(msg, self.line, self.col))
968 fn parse_value(&mut self) -> DecodeResult<Json> {
969 self.parse_whitespace();
971 if self.eof() { return self.error(~"EOF while parsing value"); }
973 match self.ch_or_null() {
974 'n' => self.parse_ident("ull", Null),
975 't' => self.parse_ident("rue", Boolean(true)),
976 'f' => self.parse_ident("alse", Boolean(false)),
977 '0' .. '9' | '-' => self.parse_number(),
979 match self.parse_str() {
980 Ok(s) => Ok(String(s)),
984 '[' => self.parse_list(),
985 '{' => self.parse_object(),
986 _ => self.error(~"invalid syntax"),
990 fn parse_whitespace(&mut self) {
991 while self.ch_is(' ') ||
994 self.ch_is('\r') { self.bump(); }
997 fn parse_ident(&mut self, ident: &str, value: Json) -> DecodeResult<Json> {
998 if ident.chars().all(|c| Some(c) == self.next_char()) {
1002 self.error(~"invalid syntax")
1006 fn parse_number(&mut self) -> DecodeResult<Json> {
1009 if self.ch_is('-') {
1014 let mut res = match self.parse_integer() {
1016 Err(e) => return Err(e)
1019 if self.ch_is('.') {
1020 match self.parse_decimal(res) {
1022 Err(e) => return Err(e)
1026 if self.ch_is('e') || self.ch_is('E') {
1027 match self.parse_exponent(res) {
1029 Err(e) => return Err(e)
1033 Ok(Number(neg * res))
1036 fn parse_integer(&mut self) -> DecodeResult<f64> {
1039 match self.ch_or_null() {
1043 // There can be only one leading '0'.
1044 match self.ch_or_null() {
1045 '0' .. '9' => return self.error(~"invalid number"),
1051 match self.ch_or_null() {
1054 res += ((c as int) - ('0' as int)) as f64;
1062 _ => return self.error(~"invalid number"),
1067 fn parse_decimal(&mut self, res: f64) -> DecodeResult<f64> {
1070 // Make sure a digit follows the decimal place.
1071 match self.ch_or_null() {
1073 _ => return self.error(~"invalid number")
1079 match self.ch_or_null() {
1082 res += (((c as int) - ('0' as int)) as f64) * dec;
1093 fn parse_exponent(&mut self, mut res: f64) -> DecodeResult<f64> {
1097 let mut neg_exp = false;
1099 if self.ch_is('+') {
1101 } else if self.ch_is('-') {
1106 // Make sure a digit follows the exponent place.
1107 match self.ch_or_null() {
1109 _ => return self.error(~"invalid number")
1112 match self.ch_or_null() {
1115 exp += (c as uint) - ('0' as uint);
1123 let exp: f64 = num::pow(10u as f64, exp);
1133 fn decode_hex_escape(&mut self) -> DecodeResult<u16> {
1136 while i < 4u && !self.eof() {
1138 n = match self.ch_or_null() {
1139 c @ '0' .. '9' => n * 16_u16 + ((c as u16) - ('0' as u16)),
1140 'a' | 'A' => n * 16_u16 + 10_u16,
1141 'b' | 'B' => n * 16_u16 + 11_u16,
1142 'c' | 'C' => n * 16_u16 + 12_u16,
1143 'd' | 'D' => n * 16_u16 + 13_u16,
1144 'e' | 'E' => n * 16_u16 + 14_u16,
1145 'f' | 'F' => n * 16_u16 + 15_u16,
1146 _ => return self.error(
1147 ~"invalid \\u escape (unrecognized hex)")
1153 // Error out if we didn't parse 4 digits.
1156 ~"invalid \\u escape (not four digits)");
1162 fn parse_str(&mut self) -> DecodeResult<~str> {
1163 let mut escape = false;
1164 let mut res = StrBuf::new();
1169 return self.error(~"EOF while parsing string");
1173 match self.ch_or_null() {
1174 '"' => res.push_char('"'),
1175 '\\' => res.push_char('\\'),
1176 '/' => res.push_char('/'),
1177 'b' => res.push_char('\x08'),
1178 'f' => res.push_char('\x0c'),
1179 'n' => res.push_char('\n'),
1180 'r' => res.push_char('\r'),
1181 't' => res.push_char('\t'),
1182 'u' => match try!(self.decode_hex_escape()) {
1183 0xDC00 .. 0xDFFF => return self.error(
1184 ~"lone trailing surrogate in hex escape"),
1186 // Non-BMP characters are encoded as a sequence of
1187 // two hex escapes, representing UTF-16 surrogates.
1188 n1 @ 0xD800 .. 0xDBFF => {
1189 let c1 = self.next_char();
1190 let c2 = self.next_char();
1192 (Some('\\'), Some('u')) => (),
1193 _ => return self.error(
1194 ~"unexpected end of non-BMP hex escape"),
1197 let buf = [n1, try!(self.decode_hex_escape())];
1198 match str::utf16_items(buf.as_slice()).next() {
1199 Some(ScalarValue(c)) => res.push_char(c),
1200 _ => return self.error(
1201 ~"lone leading surrogate in hex escape"),
1205 n => match char::from_u32(n as u32) {
1206 Some(c) => res.push_char(c),
1207 None => return self.error(
1208 format!("invalid Unicode codepoint {:u}", n)),
1211 _ => return self.error(~"invalid escape"),
1214 } else if self.ch_is('\\') {
1220 return Ok(res.into_owned());
1222 Some(c) => res.push_char(c),
1223 None => unreachable!()
1229 fn parse_list(&mut self) -> DecodeResult<Json> {
1231 self.parse_whitespace();
1233 let mut values = Vec::new();
1235 if self.ch_is(']') {
1237 return Ok(List(values.move_iter().collect()));
1241 match self.parse_value() {
1242 Ok(v) => values.push(v),
1243 Err(e) => return Err(e)
1246 self.parse_whitespace();
1248 return self.error(~"EOF while parsing list");
1251 if self.ch_is(',') {
1253 } else if self.ch_is(']') {
1255 return Ok(List(values.move_iter().collect()));
1257 return self.error(~"expected `,` or `]`")
1262 fn parse_object(&mut self) -> DecodeResult<Json> {
1264 self.parse_whitespace();
1266 let mut values = ~TreeMap::new();
1268 if self.ch_is('}') {
1270 return Ok(Object(values));
1274 self.parse_whitespace();
1276 if !self.ch_is('"') {
1277 return self.error(~"key must be a string");
1280 let key = match self.parse_str() {
1282 Err(e) => return Err(e)
1285 self.parse_whitespace();
1287 if !self.ch_is(':') {
1288 if self.eof() { break; }
1289 return self.error(~"expected `:`");
1293 match self.parse_value() {
1294 Ok(value) => { values.insert(key, value); }
1295 Err(e) => return Err(e)
1297 self.parse_whitespace();
1299 match self.ch_or_null() {
1301 '}' => { self.bump(); return Ok(Object(values)); },
1303 if self.eof() { break; }
1304 return self.error(~"expected `,` or `}`");
1309 return self.error(~"EOF while parsing object");
1313 /// Decodes a json value from an `&mut io::Reader`
1314 pub fn from_reader(rdr: &mut io::Reader) -> DecodeResult<Json> {
1315 let contents = match rdr.read_to_end() {
1317 Err(e) => return Err(IoError(e))
1319 let s = match str::from_utf8(contents.as_slice()) {
1320 Some(s) => s.to_owned(),
1321 None => return Err(ParseError(~"contents not utf-8", 0, 0))
1323 let mut parser = Parser::new(s.chars());
1327 /// Decodes a json value from a string
1328 pub fn from_str(s: &str) -> DecodeResult<Json> {
1329 let mut parser = Parser::new(s.chars());
1333 /// A structure to decode JSON to values in rust.
1334 pub struct Decoder {
1339 /// Creates a new decoder instance for decoding the specified JSON value.
1340 pub fn new(json: Json) -> Decoder {
1348 fn pop(&mut self) -> Json {
1349 self.stack.pop().unwrap()
1353 macro_rules! expect(
1354 ($e:expr, Null) => ({
1357 other => Err(ExpectedError(~"Null", format!("{}", other)))
1360 ($e:expr, $t:ident) => ({
1363 other => Err(ExpectedError(stringify!($t).to_owned(), format!("{}", other)))
1368 impl ::Decoder<Error> for Decoder {
1369 fn read_nil(&mut self) -> DecodeResult<()> {
1371 try!(expect!(self.pop(), Null));
1375 fn read_u64(&mut self) -> DecodeResult<u64 > { Ok(try!(self.read_f64()) as u64) }
1376 fn read_u32(&mut self) -> DecodeResult<u32 > { Ok(try!(self.read_f64()) as u32) }
1377 fn read_u16(&mut self) -> DecodeResult<u16 > { Ok(try!(self.read_f64()) as u16) }
1378 fn read_u8 (&mut self) -> DecodeResult<u8 > { Ok(try!(self.read_f64()) as u8) }
1379 fn read_uint(&mut self) -> DecodeResult<uint> { Ok(try!(self.read_f64()) as uint) }
1381 fn read_i64(&mut self) -> DecodeResult<i64> { Ok(try!(self.read_f64()) as i64) }
1382 fn read_i32(&mut self) -> DecodeResult<i32> { Ok(try!(self.read_f64()) as i32) }
1383 fn read_i16(&mut self) -> DecodeResult<i16> { Ok(try!(self.read_f64()) as i16) }
1384 fn read_i8 (&mut self) -> DecodeResult<i8 > { Ok(try!(self.read_f64()) as i8) }
1385 fn read_int(&mut self) -> DecodeResult<int> { Ok(try!(self.read_f64()) as int) }
1387 fn read_bool(&mut self) -> DecodeResult<bool> {
1388 debug!("read_bool");
1389 Ok(try!(expect!(self.pop(), Boolean)))
1392 fn read_f64(&mut self) -> DecodeResult<f64> {
1393 use std::from_str::FromStr;
1398 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
1399 // is going to have a string here, as per JSON spec..
1400 Ok(FromStr::from_str(s).unwrap())
1402 value => Err(ExpectedError(~"Number", format!("{}", value)))
1406 fn read_f32(&mut self) -> DecodeResult<f32> { Ok(try!(self.read_f64()) as f32) }
1408 fn read_char(&mut self) -> DecodeResult<char> {
1409 let s = try!(self.read_str());
1411 let mut it = s.chars();
1412 match (it.next(), it.next()) {
1413 // exactly one character
1414 (Some(c), None) => return Ok(c),
1418 Err(ExpectedError(~"single character string", format!("{}", s)))
1421 fn read_str(&mut self) -> DecodeResult<~str> {
1423 Ok(try!(expect!(self.pop(), String)))
1426 fn read_enum<T>(&mut self,
1428 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
1429 debug!("read_enum({})", name);
1433 fn read_enum_variant<T>(&mut self,
1435 f: |&mut Decoder, uint| -> DecodeResult<T>)
1436 -> DecodeResult<T> {
1437 debug!("read_enum_variant(names={:?})", names);
1438 let name = match self.pop() {
1441 let n = match o.pop(&~"variant") {
1442 Some(String(s)) => s,
1443 Some(val) => return Err(ExpectedError(~"String", format!("{}", val))),
1444 None => return Err(MissingFieldError(~"variant"))
1446 match o.pop(&~"fields") {
1448 for field in l.move_rev_iter() {
1449 self.stack.push(field.clone());
1452 Some(val) => return Err(ExpectedError(~"List", format!("{}", val))),
1453 None => return Err(MissingFieldError(~"fields"))
1457 json => return Err(ExpectedError(~"String or Object", format!("{}", json)))
1459 let idx = match names.iter().position(|n| str::eq_slice(*n, name)) {
1461 None => return Err(UnknownVariantError(name))
1466 fn read_enum_variant_arg<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
1467 -> DecodeResult<T> {
1468 debug!("read_enum_variant_arg(idx={})", idx);
1472 fn read_enum_struct_variant<T>(&mut self,
1474 f: |&mut Decoder, uint| -> DecodeResult<T>)
1475 -> DecodeResult<T> {
1476 debug!("read_enum_struct_variant(names={:?})", names);
1477 self.read_enum_variant(names, f)
1481 fn read_enum_struct_variant_field<T>(&mut self,
1484 f: |&mut Decoder| -> DecodeResult<T>)
1485 -> DecodeResult<T> {
1486 debug!("read_enum_struct_variant_field(name={}, idx={})", name, idx);
1487 self.read_enum_variant_arg(idx, f)
1490 fn read_struct<T>(&mut self,
1493 f: |&mut Decoder| -> DecodeResult<T>)
1494 -> DecodeResult<T> {
1495 debug!("read_struct(name={}, len={})", name, len);
1496 let value = try!(f(self));
1501 fn read_struct_field<T>(&mut self,
1504 f: |&mut Decoder| -> DecodeResult<T>)
1505 -> DecodeResult<T> {
1506 debug!("read_struct_field(name={}, idx={})", name, idx);
1507 let mut obj = try!(expect!(self.pop(), Object));
1509 let value = match obj.pop(&name.to_owned()) {
1510 None => return Err(MissingFieldError(name.to_owned())),
1512 self.stack.push(json);
1516 self.stack.push(Object(obj));
1520 fn read_tuple<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
1521 debug!("read_tuple()");
1525 fn read_tuple_arg<T>(&mut self,
1527 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
1528 debug!("read_tuple_arg(idx={})", idx);
1529 self.read_seq_elt(idx, f)
1532 fn read_tuple_struct<T>(&mut self,
1534 f: |&mut Decoder, uint| -> DecodeResult<T>)
1535 -> DecodeResult<T> {
1536 debug!("read_tuple_struct(name={})", name);
1540 fn read_tuple_struct_arg<T>(&mut self,
1542 f: |&mut Decoder| -> DecodeResult<T>)
1543 -> DecodeResult<T> {
1544 debug!("read_tuple_struct_arg(idx={})", idx);
1545 self.read_tuple_arg(idx, f)
1548 fn read_option<T>(&mut self, f: |&mut Decoder, bool| -> DecodeResult<T>) -> DecodeResult<T> {
1550 Null => f(self, false),
1551 value => { self.stack.push(value); f(self, true) }
1555 fn read_seq<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
1556 debug!("read_seq()");
1557 let list = try!(expect!(self.pop(), List));
1558 let len = list.len();
1559 for v in list.move_rev_iter() {
1565 fn read_seq_elt<T>(&mut self,
1567 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
1568 debug!("read_seq_elt(idx={})", idx);
1572 fn read_map<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
1573 debug!("read_map()");
1574 let obj = try!(expect!(self.pop(), Object));
1575 let len = obj.len();
1576 for (key, value) in obj.move_iter() {
1577 self.stack.push(value);
1578 self.stack.push(String(key));
1583 fn read_map_elt_key<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
1584 -> DecodeResult<T> {
1585 debug!("read_map_elt_key(idx={})", idx);
1589 fn read_map_elt_val<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
1590 -> DecodeResult<T> {
1591 debug!("read_map_elt_val(idx={})", idx);
1596 /// Test if two json values are less than one another
1598 fn lt(&self, other: &Json) -> bool {
1602 Number(f1) => f0 < f1,
1603 String(_) | Boolean(_) | List(_) | Object(_) |
1611 String(ref s1) => s0 < s1,
1612 Boolean(_) | List(_) | Object(_) | Null => true
1618 Number(_) | String(_) => false,
1619 Boolean(b1) => b0 < b1,
1620 List(_) | Object(_) | Null => true
1626 Number(_) | String(_) | Boolean(_) => false,
1627 List(ref l1) => (*l0) < (*l1),
1628 Object(_) | Null => true
1634 Number(_) | String(_) | Boolean(_) | List(_) => false,
1635 Object(ref d1) => d0 < d1,
1642 Number(_) | String(_) | Boolean(_) | List(_) |
1652 /// A trait for converting values to JSON
1654 /// Converts the value of `self` to an instance of JSON
1655 fn to_json(&self) -> Json;
1658 impl ToJson for Json {
1659 fn to_json(&self) -> Json { (*self).clone() }
1662 impl ToJson for int {
1663 fn to_json(&self) -> Json { Number(*self as f64) }
1666 impl ToJson for i8 {
1667 fn to_json(&self) -> Json { Number(*self as f64) }
1670 impl ToJson for i16 {
1671 fn to_json(&self) -> Json { Number(*self as f64) }
1674 impl ToJson for i32 {
1675 fn to_json(&self) -> Json { Number(*self as f64) }
1678 impl ToJson for i64 {
1679 fn to_json(&self) -> Json { Number(*self as f64) }
1682 impl ToJson for uint {
1683 fn to_json(&self) -> Json { Number(*self as f64) }
1686 impl ToJson for u8 {
1687 fn to_json(&self) -> Json { Number(*self as f64) }
1690 impl ToJson for u16 {
1691 fn to_json(&self) -> Json { Number(*self as f64) }
1694 impl ToJson for u32 {
1695 fn to_json(&self) -> Json { Number(*self as f64) }
1698 impl ToJson for u64 {
1699 fn to_json(&self) -> Json { Number(*self as f64) }
1702 impl ToJson for f32 {
1703 fn to_json(&self) -> Json { Number(*self as f64) }
1706 impl ToJson for f64 {
1707 fn to_json(&self) -> Json { Number(*self) }
1710 impl ToJson for () {
1711 fn to_json(&self) -> Json { Null }
1714 impl ToJson for bool {
1715 fn to_json(&self) -> Json { Boolean(*self) }
1718 impl ToJson for ~str {
1719 fn to_json(&self) -> Json { String((*self).clone()) }
1722 impl<A:ToJson,B:ToJson> ToJson for (A, B) {
1723 fn to_json(&self) -> Json {
1726 List(~[a.to_json(), b.to_json()])
1732 impl<A:ToJson,B:ToJson,C:ToJson> ToJson for (A, B, C) {
1733 fn to_json(&self) -> Json {
1735 (ref a, ref b, ref c) => {
1736 List(~[a.to_json(), b.to_json(), c.to_json()])
1742 impl<A:ToJson> ToJson for ~[A] {
1743 fn to_json(&self) -> Json { List(self.iter().map(|elt| elt.to_json()).collect()) }
1746 impl<A:ToJson> ToJson for TreeMap<~str, A> {
1747 fn to_json(&self) -> Json {
1748 let mut d = TreeMap::new();
1749 for (key, value) in self.iter() {
1750 d.insert((*key).clone(), value.to_json());
1756 impl<A:ToJson> ToJson for HashMap<~str, A> {
1757 fn to_json(&self) -> Json {
1758 let mut d = TreeMap::new();
1759 for (key, value) in self.iter() {
1760 d.insert((*key).clone(), value.to_json());
1766 impl<A:ToJson> ToJson for Option<A> {
1767 fn to_json(&self) -> Json {
1770 Some(ref value) => value.to_json()
1775 impl fmt::Show for Json {
1776 /// Encodes a json value into a string
1777 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1778 self.to_writer(f.buf)
1784 use {Encodable, Decodable};
1785 use super::{Encoder, Decoder, Error, Boolean, Number, List, String, Null,
1786 PrettyEncoder, Object, Json, from_str, ParseError, ExpectedError,
1787 MissingFieldError, UnknownVariantError, DecodeResult };
1789 use collections::TreeMap;
1791 #[deriving(Eq, Encodable, Decodable, Show)]
1797 #[deriving(Eq, Encodable, Decodable, Show)]
1804 #[deriving(Eq, Encodable, Decodable, Show)]
1809 fn mk_object(items: &[(~str, Json)]) -> Json {
1810 let mut d = ~TreeMap::new();
1812 for item in items.iter() {
1814 (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
1822 fn test_write_null() {
1823 assert_eq!(Null.to_str(), ~"null");
1824 assert_eq!(Null.to_pretty_str(), ~"null");
1829 fn test_write_number() {
1830 assert_eq!(Number(3.0).to_str(), ~"3");
1831 assert_eq!(Number(3.0).to_pretty_str(), ~"3");
1833 assert_eq!(Number(3.1).to_str(), ~"3.1");
1834 assert_eq!(Number(3.1).to_pretty_str(), ~"3.1");
1836 assert_eq!(Number(-1.5).to_str(), ~"-1.5");
1837 assert_eq!(Number(-1.5).to_pretty_str(), ~"-1.5");
1839 assert_eq!(Number(0.5).to_str(), ~"0.5");
1840 assert_eq!(Number(0.5).to_pretty_str(), ~"0.5");
1844 fn test_write_str() {
1845 assert_eq!(String(~"").to_str(), ~"\"\"");
1846 assert_eq!(String(~"").to_pretty_str(), ~"\"\"");
1848 assert_eq!(String(~"foo").to_str(), ~"\"foo\"");
1849 assert_eq!(String(~"foo").to_pretty_str(), ~"\"foo\"");
1853 fn test_write_bool() {
1854 assert_eq!(Boolean(true).to_str(), ~"true");
1855 assert_eq!(Boolean(true).to_pretty_str(), ~"true");
1857 assert_eq!(Boolean(false).to_str(), ~"false");
1858 assert_eq!(Boolean(false).to_pretty_str(), ~"false");
1862 fn test_write_list() {
1863 assert_eq!(List(~[]).to_str(), ~"[]");
1864 assert_eq!(List(~[]).to_pretty_str(), ~"[]");
1866 assert_eq!(List(~[Boolean(true)]).to_str(), ~"[true]");
1868 List(~[Boolean(true)]).to_pretty_str(),
1875 let long_test_list = List(~[
1878 List(~[String(~"foo\nbar"), Number(3.5)])]);
1880 assert_eq!(long_test_list.to_str(),
1881 ~"[false,null,[\"foo\\nbar\",3.5]]");
1883 long_test_list.to_pretty_str(),
1897 fn test_write_object() {
1898 assert_eq!(mk_object([]).to_str(), ~"{}");
1899 assert_eq!(mk_object([]).to_pretty_str(), ~"{}");
1902 mk_object([(~"a", Boolean(true))]).to_str(),
1906 mk_object([(~"a", Boolean(true))]).to_pretty_str(),
1913 let complex_obj = mk_object([
1915 mk_object([(~"c", String(~"\x0c\r"))]),
1916 mk_object([(~"d", String(~""))])
1921 complex_obj.to_str(),
1924 {\"c\":\"\\f\\r\"},\
1930 complex_obj.to_pretty_str(),
1935 \"c\": \"\\f\\r\"\n \
1945 (~"a", Boolean(true)),
1947 mk_object([(~"c", String(~"\x0c\r"))]),
1948 mk_object([(~"d", String(~""))])
1952 // We can't compare the strings directly because the object fields be
1953 // printed in a different order.
1954 assert_eq!(a.clone(), from_str(a.to_str()).unwrap());
1955 assert_eq!(a.clone(), from_str(a.to_pretty_str()).unwrap());
1958 fn with_str_writer(f: |&mut io::Writer|) -> ~str {
1959 use std::io::MemWriter;
1962 let mut m = MemWriter::new();
1963 f(&mut m as &mut io::Writer);
1964 str::from_utf8(m.unwrap().as_slice()).unwrap().to_owned()
1968 fn test_write_enum() {
1971 with_str_writer(|wr| {
1972 let mut encoder = Encoder::new(wr);
1973 animal.encode(&mut encoder).unwrap();
1978 with_str_writer(|wr| {
1979 let mut encoder = PrettyEncoder::new(wr);
1980 animal.encode(&mut encoder).unwrap();
1985 let animal = Frog(~"Henry", 349);
1987 with_str_writer(|wr| {
1988 let mut encoder = Encoder::new(wr);
1989 animal.encode(&mut encoder).unwrap();
1991 ~"{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
1994 with_str_writer(|wr| {
1995 let mut encoder = PrettyEncoder::new(wr);
1996 animal.encode(&mut encoder).unwrap();
2008 fn test_write_some() {
2009 let value = Some(~"jodhpurs");
2010 let s = with_str_writer(|wr| {
2011 let mut encoder = Encoder::new(wr);
2012 value.encode(&mut encoder).unwrap();
2014 assert_eq!(s, ~"\"jodhpurs\"");
2016 let value = Some(~"jodhpurs");
2017 let s = with_str_writer(|wr| {
2018 let mut encoder = PrettyEncoder::new(wr);
2019 value.encode(&mut encoder).unwrap();
2021 assert_eq!(s, ~"\"jodhpurs\"");
2025 fn test_write_none() {
2026 let value: Option<~str> = None;
2027 let s = with_str_writer(|wr| {
2028 let mut encoder = Encoder::new(wr);
2029 value.encode(&mut encoder).unwrap();
2031 assert_eq!(s, ~"null");
2033 let s = with_str_writer(|wr| {
2034 let mut encoder = Encoder::new(wr);
2035 value.encode(&mut encoder).unwrap();
2037 assert_eq!(s, ~"null");
2041 fn test_trailing_characters() {
2042 assert_eq!(from_str("nulla"),
2043 Err(ParseError(~"trailing characters", 1u, 5u)));
2044 assert_eq!(from_str("truea"),
2045 Err(ParseError(~"trailing characters", 1u, 5u)));
2046 assert_eq!(from_str("falsea"),
2047 Err(ParseError(~"trailing characters", 1u, 6u)));
2048 assert_eq!(from_str("1a"),
2049 Err(ParseError(~"trailing characters", 1u, 2u)));
2050 assert_eq!(from_str("[]a"),
2051 Err(ParseError(~"trailing characters", 1u, 3u)));
2052 assert_eq!(from_str("{}a"),
2053 Err(ParseError(~"trailing characters", 1u, 3u)));
2057 fn test_read_identifiers() {
2058 assert_eq!(from_str("n"),
2059 Err(ParseError(~"invalid syntax", 1u, 2u)));
2060 assert_eq!(from_str("nul"),
2061 Err(ParseError(~"invalid syntax", 1u, 4u)));
2063 assert_eq!(from_str("t"),
2064 Err(ParseError(~"invalid syntax", 1u, 2u)));
2065 assert_eq!(from_str("truz"),
2066 Err(ParseError(~"invalid syntax", 1u, 4u)));
2068 assert_eq!(from_str("f"),
2069 Err(ParseError(~"invalid syntax", 1u, 2u)));
2070 assert_eq!(from_str("faz"),
2071 Err(ParseError(~"invalid syntax", 1u, 3u)));
2073 assert_eq!(from_str("null"), Ok(Null));
2074 assert_eq!(from_str("true"), Ok(Boolean(true)));
2075 assert_eq!(from_str("false"), Ok(Boolean(false)));
2076 assert_eq!(from_str(" null "), Ok(Null));
2077 assert_eq!(from_str(" true "), Ok(Boolean(true)));
2078 assert_eq!(from_str(" false "), Ok(Boolean(false)));
2082 fn test_decode_identifiers() {
2083 let mut decoder = Decoder::new(from_str("null").unwrap());
2084 let v: () = Decodable::decode(&mut decoder).unwrap();
2087 let mut decoder = Decoder::new(from_str("true").unwrap());
2088 let v: bool = Decodable::decode(&mut decoder).unwrap();
2089 assert_eq!(v, true);
2091 let mut decoder = Decoder::new(from_str("false").unwrap());
2092 let v: bool = Decodable::decode(&mut decoder).unwrap();
2093 assert_eq!(v, false);
2097 fn test_read_number() {
2098 assert_eq!(from_str("+"),
2099 Err(ParseError(~"invalid syntax", 1u, 1u)));
2100 assert_eq!(from_str("."),
2101 Err(ParseError(~"invalid syntax", 1u, 1u)));
2103 assert_eq!(from_str("-"),
2104 Err(ParseError(~"invalid number", 1u, 2u)));
2105 assert_eq!(from_str("00"),
2106 Err(ParseError(~"invalid number", 1u, 2u)));
2107 assert_eq!(from_str("1."),
2108 Err(ParseError(~"invalid number", 1u, 3u)));
2109 assert_eq!(from_str("1e"),
2110 Err(ParseError(~"invalid number", 1u, 3u)));
2111 assert_eq!(from_str("1e+"),
2112 Err(ParseError(~"invalid number", 1u, 4u)));
2114 assert_eq!(from_str("3"), Ok(Number(3.0)));
2115 assert_eq!(from_str("3.1"), Ok(Number(3.1)));
2116 assert_eq!(from_str("-1.2"), Ok(Number(-1.2)));
2117 assert_eq!(from_str("0.4"), Ok(Number(0.4)));
2118 assert_eq!(from_str("0.4e5"), Ok(Number(0.4e5)));
2119 assert_eq!(from_str("0.4e+15"), Ok(Number(0.4e15)));
2120 assert_eq!(from_str("0.4e-01"), Ok(Number(0.4e-01)));
2121 assert_eq!(from_str(" 3 "), Ok(Number(3.0)));
2125 fn test_decode_numbers() {
2126 let mut decoder = Decoder::new(from_str("3").unwrap());
2127 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2130 let mut decoder = Decoder::new(from_str("3.1").unwrap());
2131 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2134 let mut decoder = Decoder::new(from_str("-1.2").unwrap());
2135 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2136 assert_eq!(v, -1.2);
2138 let mut decoder = Decoder::new(from_str("0.4").unwrap());
2139 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2142 let mut decoder = Decoder::new(from_str("0.4e5").unwrap());
2143 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2144 assert_eq!(v, 0.4e5);
2146 let mut decoder = Decoder::new(from_str("0.4e15").unwrap());
2147 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2148 assert_eq!(v, 0.4e15);
2150 let mut decoder = Decoder::new(from_str("0.4e-01").unwrap());
2151 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2152 assert_eq!(v, 0.4e-01);
2156 fn test_read_str() {
2157 assert_eq!(from_str("\""),
2158 Err(ParseError(~"EOF while parsing string", 1u, 2u)));
2159 assert_eq!(from_str("\"lol"),
2160 Err(ParseError(~"EOF while parsing string", 1u, 5u)));
2162 assert_eq!(from_str("\"\""), Ok(String(~"")));
2163 assert_eq!(from_str("\"foo\""), Ok(String(~"foo")));
2164 assert_eq!(from_str("\"\\\"\""), Ok(String(~"\"")));
2165 assert_eq!(from_str("\"\\b\""), Ok(String(~"\x08")));
2166 assert_eq!(from_str("\"\\n\""), Ok(String(~"\n")));
2167 assert_eq!(from_str("\"\\r\""), Ok(String(~"\r")));
2168 assert_eq!(from_str("\"\\t\""), Ok(String(~"\t")));
2169 assert_eq!(from_str(" \"foo\" "), Ok(String(~"foo")));
2170 assert_eq!(from_str("\"\\u12ab\""), Ok(String(~"\u12ab")));
2171 assert_eq!(from_str("\"\\uAB12\""), Ok(String(~"\uAB12")));
2173 // Non-BMP escapes. The exact error messages and positions are kind of
2175 assert_eq!(from_str("\"\\ud83d\\udca9\""), Ok(String(~"\U0001F4A9")));
2176 assert!(from_str("\"\\ud83d\"").is_err());
2177 assert!(from_str("\"\\udca9\"").is_err());
2178 assert!(from_str("\"\\ud83d\\ud83d\"").is_err());
2179 assert!(from_str("\"\\ud83dx\"").is_err());
2180 assert!(from_str("\"\\udca9\\udca9\"").is_err());
2181 assert!(from_str("\"\\udca9x\"").is_err());
2185 fn test_decode_str() {
2186 let mut decoder = Decoder::new(from_str("\"\"").unwrap());
2187 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2190 let mut decoder = Decoder::new(from_str("\"foo\"").unwrap());
2191 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2192 assert_eq!(v, ~"foo");
2194 let mut decoder = Decoder::new(from_str("\"\\\"\"").unwrap());
2195 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2196 assert_eq!(v, ~"\"");
2198 let mut decoder = Decoder::new(from_str("\"\\b\"").unwrap());
2199 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2200 assert_eq!(v, ~"\x08");
2202 let mut decoder = Decoder::new(from_str("\"\\n\"").unwrap());
2203 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2204 assert_eq!(v, ~"\n");
2206 let mut decoder = Decoder::new(from_str("\"\\r\"").unwrap());
2207 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2208 assert_eq!(v, ~"\r");
2210 let mut decoder = Decoder::new(from_str("\"\\t\"").unwrap());
2211 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2212 assert_eq!(v, ~"\t");
2214 let mut decoder = Decoder::new(from_str("\"\\u12ab\"").unwrap());
2215 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2216 assert_eq!(v, ~"\u12ab");
2218 let mut decoder = Decoder::new(from_str("\"\\uAB12\"").unwrap());
2219 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2220 assert_eq!(v, ~"\uAB12");
2224 fn test_read_list() {
2225 assert_eq!(from_str("["),
2226 Err(ParseError(~"EOF while parsing value", 1u, 2u)));
2227 assert_eq!(from_str("[1"),
2228 Err(ParseError(~"EOF while parsing list", 1u, 3u)));
2229 assert_eq!(from_str("[1,"),
2230 Err(ParseError(~"EOF while parsing value", 1u, 4u)));
2231 assert_eq!(from_str("[1,]"),
2232 Err(ParseError(~"invalid syntax", 1u, 4u)));
2233 assert_eq!(from_str("[6 7]"),
2234 Err(ParseError(~"expected `,` or `]`", 1u, 4u)));
2236 assert_eq!(from_str("[]"), Ok(List(~[])));
2237 assert_eq!(from_str("[ ]"), Ok(List(~[])));
2238 assert_eq!(from_str("[true]"), Ok(List(~[Boolean(true)])));
2239 assert_eq!(from_str("[ false ]"), Ok(List(~[Boolean(false)])));
2240 assert_eq!(from_str("[null]"), Ok(List(~[Null])));
2241 assert_eq!(from_str("[3, 1]"),
2242 Ok(List(~[Number(3.0), Number(1.0)])));
2243 assert_eq!(from_str("\n[3, 2]\n"),
2244 Ok(List(~[Number(3.0), Number(2.0)])));
2245 assert_eq!(from_str("[2, [4, 1]]"),
2246 Ok(List(~[Number(2.0), List(~[Number(4.0), Number(1.0)])])));
2250 fn test_decode_list() {
2251 let mut decoder = Decoder::new(from_str("[]").unwrap());
2252 let v: ~[()] = Decodable::decode(&mut decoder).unwrap();
2255 let mut decoder = Decoder::new(from_str("[null]").unwrap());
2256 let v: ~[()] = Decodable::decode(&mut decoder).unwrap();
2257 assert_eq!(v, ~[()]);
2259 let mut decoder = Decoder::new(from_str("[true]").unwrap());
2260 let v: ~[bool] = Decodable::decode(&mut decoder).unwrap();
2261 assert_eq!(v, ~[true]);
2263 let mut decoder = Decoder::new(from_str("[true]").unwrap());
2264 let v: ~[bool] = Decodable::decode(&mut decoder).unwrap();
2265 assert_eq!(v, ~[true]);
2267 let mut decoder = Decoder::new(from_str("[3, 1]").unwrap());
2268 let v: ~[int] = Decodable::decode(&mut decoder).unwrap();
2269 assert_eq!(v, ~[3, 1]);
2271 let mut decoder = Decoder::new(from_str("[[3], [1, 2]]").unwrap());
2272 let v: ~[~[uint]] = Decodable::decode(&mut decoder).unwrap();
2273 assert_eq!(v, ~[~[3], ~[1, 2]]);
2277 fn test_read_object() {
2278 assert_eq!(from_str("{"),
2279 Err(ParseError(~"EOF while parsing object", 1u, 2u)));
2280 assert_eq!(from_str("{ "),
2281 Err(ParseError(~"EOF while parsing object", 1u, 3u)));
2282 assert_eq!(from_str("{1"),
2283 Err(ParseError(~"key must be a string", 1u, 2u)));
2284 assert_eq!(from_str("{ \"a\""),
2285 Err(ParseError(~"EOF while parsing object", 1u, 6u)));
2286 assert_eq!(from_str("{\"a\""),
2287 Err(ParseError(~"EOF while parsing object", 1u, 5u)));
2288 assert_eq!(from_str("{\"a\" "),
2289 Err(ParseError(~"EOF while parsing object", 1u, 6u)));
2291 assert_eq!(from_str("{\"a\" 1"),
2292 Err(ParseError(~"expected `:`", 1u, 6u)));
2293 assert_eq!(from_str("{\"a\":"),
2294 Err(ParseError(~"EOF while parsing value", 1u, 6u)));
2295 assert_eq!(from_str("{\"a\":1"),
2296 Err(ParseError(~"EOF while parsing object", 1u, 7u)));
2297 assert_eq!(from_str("{\"a\":1 1"),
2298 Err(ParseError(~"expected `,` or `}`", 1u, 8u)));
2299 assert_eq!(from_str("{\"a\":1,"),
2300 Err(ParseError(~"EOF while parsing object", 1u, 8u)));
2302 assert_eq!(from_str("{}").unwrap(), mk_object([]));
2303 assert_eq!(from_str("{\"a\": 3}").unwrap(),
2304 mk_object([(~"a", Number(3.0))]));
2306 assert_eq!(from_str(
2307 "{ \"a\": null, \"b\" : true }").unwrap(),
2310 (~"b", Boolean(true))]));
2311 assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
2314 (~"b", Boolean(true))]));
2315 assert_eq!(from_str(
2316 "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
2318 (~"a", Number(1.0)),
2319 (~"b", List(~[Boolean(true)]))
2321 assert_eq!(from_str(
2327 "{ \"c\": {\"d\": null} } " +
2331 (~"a", Number(1.0)),
2334 String(~"foo\nbar"),
2336 (~"c", mk_object([(~"d", Null)]))
2343 fn test_decode_struct() {
2346 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
2349 let mut decoder = Decoder::new(from_str(s).unwrap());
2350 let v: Outer = Decodable::decode(&mut decoder).unwrap();
2355 Inner { a: (), b: 2, c: ~[~"abc", ~"xyz"] }
2362 fn test_decode_option() {
2363 let mut decoder = Decoder::new(from_str("null").unwrap());
2364 let value: Option<~str> = Decodable::decode(&mut decoder).unwrap();
2365 assert_eq!(value, None);
2367 let mut decoder = Decoder::new(from_str("\"jodhpurs\"").unwrap());
2368 let value: Option<~str> = Decodable::decode(&mut decoder).unwrap();
2369 assert_eq!(value, Some(~"jodhpurs"));
2373 fn test_decode_enum() {
2374 let mut decoder = Decoder::new(from_str("\"Dog\"").unwrap());
2375 let value: Animal = Decodable::decode(&mut decoder).unwrap();
2376 assert_eq!(value, Dog);
2378 let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
2379 let mut decoder = Decoder::new(from_str(s).unwrap());
2380 let value: Animal = Decodable::decode(&mut decoder).unwrap();
2381 assert_eq!(value, Frog(~"Henry", 349));
2385 fn test_decode_map() {
2386 let s = ~"{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\"fields\":[\"Henry\", 349]}}";
2387 let mut decoder = Decoder::new(from_str(s).unwrap());
2388 let mut map: TreeMap<~str, Animal> = Decodable::decode(&mut decoder).unwrap();
2390 assert_eq!(map.pop(&~"a"), Some(Dog));
2391 assert_eq!(map.pop(&~"b"), Some(Frog(~"Henry", 349)));
2395 fn test_multiline_errors() {
2396 assert_eq!(from_str("{\n \"foo\":\n \"bar\""),
2397 Err(ParseError(~"EOF while parsing object", 3u, 8u)));
2400 #[deriving(Decodable)]
2401 struct DecodeStruct {
2407 #[deriving(Decodable)]
2412 fn check_err<T: Decodable<Decoder, Error>>(to_parse: &'static str, expected: Error) {
2413 let res: DecodeResult<T> = match from_str(to_parse) {
2415 Ok(json) => Decodable::decode(&mut Decoder::new(json))
2418 Ok(_) => fail!("`{}` parsed & decoded ok, expecting error `{}`",
2419 to_parse, expected),
2420 Err(ParseError(e, _, _)) => fail!("`{}` is not valid json: {}",
2423 assert_eq!(e, expected);
2429 fn test_decode_errors_struct() {
2430 check_err::<DecodeStruct>("[]", ExpectedError(~"Object", ~"[]"));
2431 check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
2432 ExpectedError(~"Number", ~"true"));
2433 check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
2434 ExpectedError(~"Boolean", ~"[]"));
2435 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
2436 ExpectedError(~"String", ~"{}"));
2437 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
2438 ExpectedError(~"List", ~"null"));
2439 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
2440 MissingFieldError(~"w"));
2443 fn test_decode_errors_enum() {
2444 check_err::<DecodeEnum>("{}",
2445 MissingFieldError(~"variant"));
2446 check_err::<DecodeEnum>("{\"variant\": 1}",
2447 ExpectedError(~"String", ~"1"));
2448 check_err::<DecodeEnum>("{\"variant\": \"A\"}",
2449 MissingFieldError(~"fields"));
2450 check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
2451 ExpectedError(~"List", ~"null"));
2452 check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
2453 UnknownVariantError(~"C"));
2458 let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
2459 let found_str = json_value.find(&~"dog");
2460 assert!(found_str.is_some() && found_str.unwrap().as_string().unwrap() == &"cat");
2464 fn test_find_path(){
2465 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
2466 let found_str = json_value.find_path(&[&~"dog", &~"cat", &~"mouse"]);
2467 assert!(found_str.is_some() && found_str.unwrap().as_string().unwrap() == &"cheese");
2472 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
2473 let found_str = json_value.search(&~"mouse").and_then(|j| j.as_string());
2474 assert!(found_str.is_some());
2475 assert!(found_str.unwrap() == &"cheese");
2479 fn test_is_object(){
2480 let json_value = from_str("{}").unwrap();
2481 assert!(json_value.is_object());
2485 fn test_as_object(){
2486 let json_value = from_str("{}").unwrap();
2487 let json_object = json_value.as_object();
2488 assert!(json_object.is_some());
2493 let json_value = from_str("[1, 2, 3]").unwrap();
2494 assert!(json_value.is_list());
2499 let json_value = from_str("[1, 2, 3]").unwrap();
2500 let json_list = json_value.as_list();
2501 let expected_length = 3;
2502 assert!(json_list.is_some() && json_list.unwrap().len() == expected_length);
2506 fn test_is_string(){
2507 let json_value = from_str("\"dog\"").unwrap();
2508 assert!(json_value.is_string());
2512 fn test_as_string(){
2513 let json_value = from_str("\"dog\"").unwrap();
2514 let json_str = json_value.as_string();
2515 let expected_str = &"dog";
2516 assert_eq!(json_str, Some(expected_str));
2520 fn test_is_number(){
2521 let json_value = from_str("12").unwrap();
2522 assert!(json_value.is_number());
2526 fn test_as_number(){
2527 let json_value = from_str("12").unwrap();
2528 let json_num = json_value.as_number();
2529 let expected_num = 12f64;
2530 assert!(json_num.is_some() && json_num.unwrap() == expected_num);
2534 fn test_is_boolean(){
2535 let json_value = from_str("false").unwrap();
2536 assert!(json_value.is_boolean());
2540 fn test_as_boolean(){
2541 let json_value = from_str("false").unwrap();
2542 let json_bool = json_value.as_boolean();
2543 let expected_bool = false;
2544 assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
2549 let json_value = from_str("null").unwrap();
2550 assert!(json_value.is_null());
2555 let json_value = from_str("null").unwrap();
2556 let json_null = json_value.as_null();
2557 let expected_null = ();
2558 assert!(json_null.is_some() && json_null.unwrap() == expected_null);
2562 fn test_encode_hashmap_with_numeric_key() {
2563 use std::str::from_utf8;
2564 use std::io::Writer;
2565 use std::io::MemWriter;
2566 use collections::HashMap;
2567 let mut hm: HashMap<uint, bool> = HashMap::new();
2569 let mut mem_buf = MemWriter::new();
2571 let mut encoder = Encoder::new(&mut mem_buf as &mut io::Writer);
2572 hm.encode(&mut encoder).unwrap();
2574 let bytes = mem_buf.unwrap();
2575 let json_str = from_utf8(bytes.as_slice()).unwrap();
2576 match from_str(json_str) {
2577 Err(_) => fail!("Unable to parse json_str: {:?}", json_str),
2578 _ => {} // it parsed and we are good to go
2582 fn test_prettyencode_hashmap_with_numeric_key() {
2583 use std::str::from_utf8;
2584 use std::io::Writer;
2585 use std::io::MemWriter;
2586 use collections::HashMap;
2587 let mut hm: HashMap<uint, bool> = HashMap::new();
2589 let mut mem_buf = MemWriter::new();
2591 let mut encoder = PrettyEncoder::new(&mut mem_buf as &mut io::Writer);
2592 hm.encode(&mut encoder).unwrap();
2594 let bytes = mem_buf.unwrap();
2595 let json_str = from_utf8(bytes.as_slice()).unwrap();
2596 match from_str(json_str) {
2597 Err(_) => fail!("Unable to parse json_str: {:?}", json_str),
2598 _ => {} // it parsed and we are good to go
2602 fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
2603 use collections::HashMap;
2605 let json_str = "{\"1\":true}";
2606 let json_obj = match from_str(json_str) {
2607 Err(_) => fail!("Unable to parse json_str: {:?}", json_str),
2610 let mut decoder = Decoder::new(json_obj);
2611 let _hm: HashMap<uint, bool> = Decodable::decode(&mut decoder).unwrap();