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".to_owned()};
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".to_owned();
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".to_owned(), self.attr1.to_json());
118 d.insert("attr2".to_owned(), self.attr2.to_json());
124 let test2: MyStruct = MyStruct {attr1: 1, attr2:"test".to_owned()};
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\"}".to_owned();
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".to_owned(), 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".to_owned(), self.data_int.to_json());
211 d.insert("data_str".to_owned(), self.data_str.to_json());
212 d.insert("data_vector".to_owned(), self.data_vector.to_json());
218 // Serialization using our impl of to_json
220 let test2: TestStruct1 = TestStruct1 {data_int: 1, data_str:"toto".to_owned(),
221 data_vector:~[2,3,4,5]};
222 let tjson: json::Json = test2.to_json();
223 let json_str: ~str = tjson.to_str();
225 // Deserialize like before.
227 let mut decoder = json::Decoder::new(json::from_str(json_str).unwrap());
228 // create the final object
229 let decoded2: TestStruct1 = Decodable::decode(&mut decoder).unwrap();
235 use collections::HashMap;
239 use std::io::MemWriter;
243 use std::str::ScalarValue;
244 use std::strbuf::StrBuf;
247 use collections::TreeMap;
249 /// Represents a json value
250 #[deriving(Clone, Eq)]
260 pub type List = ~[Json];
261 pub type Object = TreeMap<~str, Json>;
263 #[deriving(Eq, Show)]
266 ParseError(~str, uint, uint),
267 ExpectedError(~str, ~str),
268 MissingFieldError(~str),
269 UnknownVariantError(~str),
273 pub type EncodeResult = io::IoResult<()>;
274 pub type DecodeResult<T> = Result<T, Error>;
276 fn escape_str(s: &str) -> ~str {
277 let mut escaped = StrBuf::from_str("\"");
280 '"' => escaped.push_str("\\\""),
281 '\\' => escaped.push_str("\\\\"),
282 '\x08' => escaped.push_str("\\b"),
283 '\x0c' => escaped.push_str("\\f"),
284 '\n' => escaped.push_str("\\n"),
285 '\r' => escaped.push_str("\\r"),
286 '\t' => escaped.push_str("\\t"),
287 _ => escaped.push_char(c),
290 escaped.push_char('"');
294 fn spaces(n: uint) -> ~str {
295 let mut ss = StrBuf::new();
296 for _ in range(0, n) {
299 return ss.into_owned();
302 /// A structure for implementing serialization to JSON.
303 pub struct Encoder<'a> {
304 wr: &'a mut io::Writer,
307 impl<'a> Encoder<'a> {
308 /// Creates a new JSON encoder whose output will be written to the writer
310 pub fn new<'a>(wr: &'a mut io::Writer) -> Encoder<'a> {
314 /// Encode the specified struct into a json [u8]
315 pub fn buffer_encode<T:Encodable<Encoder<'a>, io::IoError>>(to_encode_object: &T) -> Vec<u8> {
316 //Serialize the object in a string using a writer
317 let mut m = MemWriter::new();
319 let mut encoder = Encoder::new(&mut m as &mut io::Writer);
320 // MemWriter never Errs
321 let _ = to_encode_object.encode(&mut encoder);
326 /// Encode the specified struct into a json str
327 pub fn str_encode<T:Encodable<Encoder<'a>, io::IoError>>(to_encode_object: &T) -> ~str {
328 let buff = Encoder::buffer_encode(to_encode_object);
329 str::from_utf8(buff.as_slice()).unwrap().to_owned()
333 impl<'a> ::Encoder<io::IoError> for Encoder<'a> {
334 fn emit_nil(&mut self) -> EncodeResult { write!(self.wr, "null") }
336 fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) }
337 fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) }
338 fn emit_u32(&mut self, v: u32) -> EncodeResult { self.emit_f64(v as f64) }
339 fn emit_u16(&mut self, v: u16) -> EncodeResult { self.emit_f64(v as f64) }
340 fn emit_u8(&mut self, v: u8) -> EncodeResult { self.emit_f64(v as f64) }
342 fn emit_int(&mut self, v: int) -> EncodeResult { self.emit_f64(v as f64) }
343 fn emit_i64(&mut self, v: i64) -> EncodeResult { self.emit_f64(v as f64) }
344 fn emit_i32(&mut self, v: i32) -> EncodeResult { self.emit_f64(v as f64) }
345 fn emit_i16(&mut self, v: i16) -> EncodeResult { self.emit_f64(v as f64) }
346 fn emit_i8(&mut self, v: i8) -> EncodeResult { self.emit_f64(v as f64) }
348 fn emit_bool(&mut self, v: bool) -> EncodeResult {
350 write!(self.wr, "true")
352 write!(self.wr, "false")
356 fn emit_f64(&mut self, v: f64) -> EncodeResult {
357 write!(self.wr, "{}", f64::to_str_digits(v, 6u))
359 fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) }
361 fn emit_char(&mut self, v: char) -> EncodeResult { self.emit_str(str::from_char(v)) }
362 fn emit_str(&mut self, v: &str) -> EncodeResult {
363 write!(self.wr, "{}", escape_str(v))
366 fn emit_enum(&mut self,
368 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult { f(self) }
370 fn emit_enum_variant(&mut self,
374 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
375 // enums are encoded as strings or objects
377 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
379 write!(self.wr, "{}", escape_str(name))
381 try!(write!(self.wr, "\\{\"variant\":"));
382 try!(write!(self.wr, "{}", escape_str(name)));
383 try!(write!(self.wr, ",\"fields\":["));
385 write!(self.wr, "]\\}")
389 fn emit_enum_variant_arg(&mut self,
391 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
393 try!(write!(self.wr, ","));
398 fn emit_enum_struct_variant(&mut self,
402 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
403 self.emit_enum_variant(name, id, cnt, f)
406 fn emit_enum_struct_variant_field(&mut self,
409 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
410 self.emit_enum_variant_arg(idx, f)
413 fn emit_struct(&mut self,
416 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
417 try!(write!(self.wr, r"\{"));
419 write!(self.wr, r"\}")
422 fn emit_struct_field(&mut self,
425 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
426 if idx != 0 { try!(write!(self.wr, ",")); }
427 try!(write!(self.wr, "{}:", escape_str(name)));
431 fn emit_tuple(&mut self, len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
432 self.emit_seq(len, f)
434 fn emit_tuple_arg(&mut self,
436 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
437 self.emit_seq_elt(idx, f)
440 fn emit_tuple_struct(&mut self,
443 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
444 self.emit_seq(len, f)
446 fn emit_tuple_struct_arg(&mut self,
448 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
449 self.emit_seq_elt(idx, f)
452 fn emit_option(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
455 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
456 fn emit_option_some(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
460 fn emit_seq(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
461 try!(write!(self.wr, "["));
466 fn emit_seq_elt(&mut self, idx: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
468 try!(write!(self.wr, ","));
473 fn emit_map(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
474 try!(write!(self.wr, r"\{"));
476 write!(self.wr, r"\}")
479 fn emit_map_elt_key(&mut self,
481 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
482 use std::str::from_utf8;
483 if idx != 0 { try!(write!(self.wr, ",")) }
484 // ref #12967, make sure to wrap a key in double quotes,
485 // in the event that its of a type that omits them (eg numbers)
486 let mut buf = MemWriter::new();
487 let mut check_encoder = Encoder::new(&mut buf);
488 try!(f(&mut check_encoder));
489 let buf = buf.unwrap();
490 let out = from_utf8(buf.as_slice()).unwrap();
491 let needs_wrapping = out.char_at(0) != '"' &&
492 out.char_at_reverse(out.len()) != '"';
493 if needs_wrapping { try!(write!(self.wr, "\"")); }
495 if needs_wrapping { try!(write!(self.wr, "\"")); }
499 fn emit_map_elt_val(&mut self,
501 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
502 try!(write!(self.wr, ":"));
507 /// Another encoder for JSON, but prints out human-readable JSON instead of
509 pub struct PrettyEncoder<'a> {
510 wr: &'a mut io::Writer,
514 impl<'a> PrettyEncoder<'a> {
515 /// Creates a new encoder whose output will be written to the specified writer
516 pub fn new<'a>(wr: &'a mut io::Writer) -> PrettyEncoder<'a> {
524 impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> {
525 fn emit_nil(&mut self) -> EncodeResult { write!(self.wr, "null") }
527 fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) }
528 fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) }
529 fn emit_u32(&mut self, v: u32) -> EncodeResult { self.emit_f64(v as f64) }
530 fn emit_u16(&mut self, v: u16) -> EncodeResult { self.emit_f64(v as f64) }
531 fn emit_u8(&mut self, v: u8) -> EncodeResult { self.emit_f64(v as f64) }
533 fn emit_int(&mut self, v: int) -> EncodeResult { self.emit_f64(v as f64) }
534 fn emit_i64(&mut self, v: i64) -> EncodeResult { self.emit_f64(v as f64) }
535 fn emit_i32(&mut self, v: i32) -> EncodeResult { self.emit_f64(v as f64) }
536 fn emit_i16(&mut self, v: i16) -> EncodeResult { self.emit_f64(v as f64) }
537 fn emit_i8(&mut self, v: i8) -> EncodeResult { self.emit_f64(v as f64) }
539 fn emit_bool(&mut self, v: bool) -> EncodeResult {
541 write!(self.wr, "true")
543 write!(self.wr, "false")
547 fn emit_f64(&mut self, v: f64) -> EncodeResult {
548 write!(self.wr, "{}", f64::to_str_digits(v, 6u))
550 fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) }
552 fn emit_char(&mut self, v: char) -> EncodeResult { self.emit_str(str::from_char(v)) }
553 fn emit_str(&mut self, v: &str) -> EncodeResult {
554 write!(self.wr, "{}", escape_str(v))
557 fn emit_enum(&mut self,
559 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
563 fn emit_enum_variant(&mut self,
567 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
569 write!(self.wr, "{}", escape_str(name))
572 try!(write!(self.wr, "[\n{}{},\n", spaces(self.indent),
576 write!(self.wr, "\n{}]", spaces(self.indent))
580 fn emit_enum_variant_arg(&mut self,
582 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
584 try!(write!(self.wr, ",\n"));
586 try!(write!(self.wr, "{}", spaces(self.indent)));
590 fn emit_enum_struct_variant(&mut self,
594 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
595 self.emit_enum_variant(name, id, cnt, f)
598 fn emit_enum_struct_variant_field(&mut self,
601 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
602 self.emit_enum_variant_arg(idx, f)
606 fn emit_struct(&mut self,
609 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
611 write!(self.wr, "\\{\\}")
613 try!(write!(self.wr, "\\{"));
617 write!(self.wr, "\n{}\\}", spaces(self.indent))
621 fn emit_struct_field(&mut self,
624 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
626 try!(write!(self.wr, "\n"));
628 try!(write!(self.wr, ",\n"));
630 try!(write!(self.wr, "{}{}: ", spaces(self.indent), escape_str(name)));
634 fn emit_tuple(&mut self,
636 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
637 self.emit_seq(len, f)
639 fn emit_tuple_arg(&mut self,
641 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
642 self.emit_seq_elt(idx, f)
645 fn emit_tuple_struct(&mut self,
648 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
649 self.emit_seq(len, f)
651 fn emit_tuple_struct_arg(&mut self,
653 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
654 self.emit_seq_elt(idx, f)
657 fn emit_option(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
660 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
661 fn emit_option_some(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
665 fn emit_seq(&mut self,
667 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
669 write!(self.wr, "[]")
671 try!(write!(self.wr, "["));
675 write!(self.wr, "\n{}]", spaces(self.indent))
679 fn emit_seq_elt(&mut self,
681 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
683 try!(write!(self.wr, "\n"));
685 try!(write!(self.wr, ",\n"));
687 try!(write!(self.wr, "{}", spaces(self.indent)));
691 fn emit_map(&mut self,
693 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
695 write!(self.wr, "\\{\\}")
697 try!(write!(self.wr, "\\{"));
701 write!(self.wr, "\n{}\\}", spaces(self.indent))
705 fn emit_map_elt_key(&mut self,
707 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
708 use std::str::from_utf8;
710 try!(write!(self.wr, "\n"));
712 try!(write!(self.wr, ",\n"));
714 try!(write!(self.wr, "{}", spaces(self.indent)));
715 // ref #12967, make sure to wrap a key in double quotes,
716 // in the event that its of a type that omits them (eg numbers)
717 let mut buf = MemWriter::new();
718 let mut check_encoder = PrettyEncoder::new(&mut buf);
719 try!(f(&mut check_encoder));
720 let buf = buf.unwrap();
721 let out = from_utf8(buf.as_slice()).unwrap();
722 let needs_wrapping = out.char_at(0) != '"' &&
723 out.char_at_reverse(out.len()) != '"';
724 if needs_wrapping { try!(write!(self.wr, "\"")); }
726 if needs_wrapping { try!(write!(self.wr, "\"")); }
730 fn emit_map_elt_val(&mut self,
732 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
733 try!(write!(self.wr, ": "));
738 impl<E: ::Encoder<S>, S> Encodable<E, S> for Json {
739 fn encode(&self, e: &mut E) -> Result<(), S> {
741 Number(v) => v.encode(e),
742 String(ref v) => v.encode(e),
743 Boolean(v) => v.encode(e),
744 List(ref v) => v.encode(e),
745 Object(ref v) => v.encode(e),
746 Null => e.emit_nil(),
752 /// Encodes a json value into a io::writer. Uses a single line.
753 pub fn to_writer(&self, wr: &mut io::Writer) -> EncodeResult {
754 let mut encoder = Encoder::new(wr);
755 self.encode(&mut encoder)
758 /// Encodes a json value into a io::writer.
759 /// Pretty-prints in a more readable format.
760 pub fn to_pretty_writer(&self, wr: &mut io::Writer) -> EncodeResult {
761 let mut encoder = PrettyEncoder::new(wr);
762 self.encode(&mut encoder)
765 /// Encodes a json value into a string
766 pub fn to_pretty_str(&self) -> ~str {
767 let mut s = MemWriter::new();
768 self.to_pretty_writer(&mut s as &mut io::Writer).unwrap();
769 str::from_utf8(s.unwrap().as_slice()).unwrap().to_owned()
772 /// If the Json value is an Object, returns the value associated with the provided key.
773 /// Otherwise, returns None.
774 pub fn find<'a>(&'a self, key: &~str) -> Option<&'a Json>{
776 &Object(ref map) => map.find(key),
781 /// Attempts to get a nested Json Object for each key in `keys`.
782 /// If any key is found not to exist, find_path will return None.
783 /// Otherwise, it will return the Json value associated with the final key.
784 pub fn find_path<'a>(&'a self, keys: &[&~str]) -> Option<&'a Json>{
785 let mut target = self;
786 for key in keys.iter() {
787 match target.find(*key) {
788 Some(t) => { target = t; },
795 /// If the Json value is an Object, performs a depth-first search until
796 /// a value associated with the provided key is found. If no value is found
797 /// or the Json value is not an Object, returns None.
798 pub fn search<'a>(&'a self, key: &~str) -> Option<&'a Json> {
800 &Object(ref map) => {
801 match map.find(key) {
802 Some(json_value) => Some(json_value),
804 let mut value : Option<&'a Json> = None;
805 for (_, v) in map.iter() {
806 value = v.search(key);
819 /// Returns true if the Json value is an Object. Returns false otherwise.
820 pub fn is_object<'a>(&'a self) -> bool {
821 self.as_object().is_some()
824 /// If the Json value is an Object, returns the associated TreeMap.
825 /// Returns None otherwise.
826 pub fn as_object<'a>(&'a self) -> Option<&'a Object> {
828 &Object(ref map) => Some(&**map),
833 /// Returns true if the Json value is a List. Returns false otherwise.
834 pub fn is_list<'a>(&'a self) -> bool {
835 self.as_list().is_some()
838 /// If the Json value is a List, returns the associated vector.
839 /// Returns None otherwise.
840 pub fn as_list<'a>(&'a self) -> Option<&'a List> {
842 &List(ref list) => Some(&*list),
847 /// Returns true if the Json value is a String. Returns false otherwise.
848 pub fn is_string<'a>(&'a self) -> bool {
849 self.as_string().is_some()
852 /// If the Json value is a String, returns the associated str.
853 /// Returns None otherwise.
854 pub fn as_string<'a>(&'a self) -> Option<&'a str> {
856 String(ref s) => Some(s.as_slice()),
861 /// Returns true if the Json value is a Number. Returns false otherwise.
862 pub fn is_number(&self) -> bool {
863 self.as_number().is_some()
866 /// If the Json value is a Number, returns the associated f64.
867 /// Returns None otherwise.
868 pub fn as_number(&self) -> Option<f64> {
870 &Number(n) => Some(n),
875 /// Returns true if the Json value is a Boolean. Returns false otherwise.
876 pub fn is_boolean(&self) -> bool {
877 self.as_boolean().is_some()
880 /// If the Json value is a Boolean, returns the associated bool.
881 /// Returns None otherwise.
882 pub fn as_boolean(&self) -> Option<bool> {
884 &Boolean(b) => Some(b),
889 /// Returns true if the Json value is a Null. Returns false otherwise.
890 pub fn is_null(&self) -> bool {
891 self.as_null().is_some()
894 /// If the Json value is a Null, returns ().
895 /// Returns None otherwise.
896 pub fn as_null(&self) -> Option<()> {
904 pub struct Parser<T> {
911 impl<T: Iterator<char>> Parser<T> {
912 /// Decode a json value from an Iterator<char>
913 pub fn new(rdr: T) -> Parser<T> {
925 impl<T: Iterator<char>> Parser<T> {
926 pub fn parse(&mut self) -> DecodeResult<Json> {
927 match self.parse_value() {
929 // Skip trailing whitespaces.
930 self.parse_whitespace();
931 // Make sure there is no trailing characters.
935 self.error("trailing characters".to_owned())
943 impl<T : Iterator<char>> Parser<T> {
944 fn eof(&self) -> bool { self.ch.is_none() }
945 fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
947 self.ch = self.rdr.next();
949 if self.ch_is('\n') {
957 fn next_char(&mut self) -> Option<char> {
961 fn ch_is(&self, c: char) -> bool {
965 fn error<T>(&self, msg: ~str) -> DecodeResult<T> {
966 Err(ParseError(msg, self.line, self.col))
969 fn parse_value(&mut self) -> DecodeResult<Json> {
970 self.parse_whitespace();
972 if self.eof() { return self.error("EOF while parsing value".to_owned()); }
974 match self.ch_or_null() {
975 'n' => self.parse_ident("ull", Null),
976 't' => self.parse_ident("rue", Boolean(true)),
977 'f' => self.parse_ident("alse", Boolean(false)),
978 '0' .. '9' | '-' => self.parse_number(),
980 match self.parse_str() {
981 Ok(s) => Ok(String(s)),
985 '[' => self.parse_list(),
986 '{' => self.parse_object(),
987 _ => self.error("invalid syntax".to_owned()),
991 fn parse_whitespace(&mut self) {
992 while self.ch_is(' ') ||
995 self.ch_is('\r') { self.bump(); }
998 fn parse_ident(&mut self, ident: &str, value: Json) -> DecodeResult<Json> {
999 if ident.chars().all(|c| Some(c) == self.next_char()) {
1003 self.error("invalid syntax".to_owned())
1007 fn parse_number(&mut self) -> DecodeResult<Json> {
1010 if self.ch_is('-') {
1015 let mut res = match self.parse_integer() {
1017 Err(e) => return Err(e)
1020 if self.ch_is('.') {
1021 match self.parse_decimal(res) {
1023 Err(e) => return Err(e)
1027 if self.ch_is('e') || self.ch_is('E') {
1028 match self.parse_exponent(res) {
1030 Err(e) => return Err(e)
1034 Ok(Number(neg * res))
1037 fn parse_integer(&mut self) -> DecodeResult<f64> {
1040 match self.ch_or_null() {
1044 // There can be only one leading '0'.
1045 match self.ch_or_null() {
1046 '0' .. '9' => return self.error("invalid number".to_owned()),
1052 match self.ch_or_null() {
1055 res += ((c as int) - ('0' as int)) as f64;
1063 _ => return self.error("invalid number".to_owned()),
1068 fn parse_decimal(&mut self, res: f64) -> DecodeResult<f64> {
1071 // Make sure a digit follows the decimal place.
1072 match self.ch_or_null() {
1074 _ => return self.error("invalid number".to_owned())
1080 match self.ch_or_null() {
1083 res += (((c as int) - ('0' as int)) as f64) * dec;
1094 fn parse_exponent(&mut self, mut res: f64) -> DecodeResult<f64> {
1098 let mut neg_exp = false;
1100 if self.ch_is('+') {
1102 } else if self.ch_is('-') {
1107 // Make sure a digit follows the exponent place.
1108 match self.ch_or_null() {
1110 _ => return self.error("invalid number".to_owned())
1113 match self.ch_or_null() {
1116 exp += (c as uint) - ('0' as uint);
1124 let exp: f64 = num::pow(10u as f64, exp);
1134 fn decode_hex_escape(&mut self) -> DecodeResult<u16> {
1137 while i < 4u && !self.eof() {
1139 n = match self.ch_or_null() {
1140 c @ '0' .. '9' => n * 16_u16 + ((c as u16) - ('0' as u16)),
1141 'a' | 'A' => n * 16_u16 + 10_u16,
1142 'b' | 'B' => n * 16_u16 + 11_u16,
1143 'c' | 'C' => n * 16_u16 + 12_u16,
1144 'd' | 'D' => n * 16_u16 + 13_u16,
1145 'e' | 'E' => n * 16_u16 + 14_u16,
1146 'f' | 'F' => n * 16_u16 + 15_u16,
1147 _ => return self.error(
1148 "invalid \\u escape (unrecognized hex)".to_owned())
1154 // Error out if we didn't parse 4 digits.
1157 "invalid \\u escape (not four digits)".to_owned());
1163 fn parse_str(&mut self) -> DecodeResult<~str> {
1164 let mut escape = false;
1165 let mut res = StrBuf::new();
1170 return self.error("EOF while parsing string".to_owned());
1174 match self.ch_or_null() {
1175 '"' => res.push_char('"'),
1176 '\\' => res.push_char('\\'),
1177 '/' => res.push_char('/'),
1178 'b' => res.push_char('\x08'),
1179 'f' => res.push_char('\x0c'),
1180 'n' => res.push_char('\n'),
1181 'r' => res.push_char('\r'),
1182 't' => res.push_char('\t'),
1183 'u' => match try!(self.decode_hex_escape()) {
1184 0xDC00 .. 0xDFFF => return self.error(
1185 "lone trailing surrogate in hex escape".to_owned()),
1187 // Non-BMP characters are encoded as a sequence of
1188 // two hex escapes, representing UTF-16 surrogates.
1189 n1 @ 0xD800 .. 0xDBFF => {
1190 let c1 = self.next_char();
1191 let c2 = self.next_char();
1193 (Some('\\'), Some('u')) => (),
1194 _ => return self.error(
1195 "unexpected end of non-BMP hex escape".to_owned()),
1198 let buf = [n1, try!(self.decode_hex_escape())];
1199 match str::utf16_items(buf.as_slice()).next() {
1200 Some(ScalarValue(c)) => res.push_char(c),
1201 _ => return self.error(
1202 "lone leading surrogate in hex escape".to_owned()),
1206 n => match char::from_u32(n as u32) {
1207 Some(c) => res.push_char(c),
1208 None => return self.error(
1209 format!("invalid Unicode codepoint {:u}", n)),
1212 _ => return self.error("invalid escape".to_owned()),
1215 } else if self.ch_is('\\') {
1221 return Ok(res.into_owned());
1223 Some(c) => res.push_char(c),
1224 None => unreachable!()
1230 fn parse_list(&mut self) -> DecodeResult<Json> {
1232 self.parse_whitespace();
1234 let mut values = Vec::new();
1236 if self.ch_is(']') {
1238 return Ok(List(values.move_iter().collect()));
1242 match self.parse_value() {
1243 Ok(v) => values.push(v),
1244 Err(e) => return Err(e)
1247 self.parse_whitespace();
1249 return self.error("EOF while parsing list".to_owned());
1252 if self.ch_is(',') {
1254 } else if self.ch_is(']') {
1256 return Ok(List(values.move_iter().collect()));
1258 return self.error("expected `,` or `]`".to_owned())
1263 fn parse_object(&mut self) -> DecodeResult<Json> {
1265 self.parse_whitespace();
1267 let mut values = ~TreeMap::new();
1269 if self.ch_is('}') {
1271 return Ok(Object(values));
1275 self.parse_whitespace();
1277 if !self.ch_is('"') {
1278 return self.error("key must be a string".to_owned());
1281 let key = match self.parse_str() {
1283 Err(e) => return Err(e)
1286 self.parse_whitespace();
1288 if !self.ch_is(':') {
1289 if self.eof() { break; }
1290 return self.error("expected `:`".to_owned());
1294 match self.parse_value() {
1295 Ok(value) => { values.insert(key, value); }
1296 Err(e) => return Err(e)
1298 self.parse_whitespace();
1300 match self.ch_or_null() {
1302 '}' => { self.bump(); return Ok(Object(values)); },
1304 if self.eof() { break; }
1305 return self.error("expected `,` or `}`".to_owned());
1310 return self.error("EOF while parsing object".to_owned());
1314 /// Decodes a json value from an `&mut io::Reader`
1315 pub fn from_reader(rdr: &mut io::Reader) -> DecodeResult<Json> {
1316 let contents = match rdr.read_to_end() {
1318 Err(e) => return Err(IoError(e))
1320 let s = match str::from_utf8(contents.as_slice()) {
1321 Some(s) => s.to_owned(),
1322 None => return Err(ParseError("contents not utf-8".to_owned(), 0, 0))
1324 let mut parser = Parser::new(s.chars());
1328 /// Decodes a json value from a string
1329 pub fn from_str(s: &str) -> DecodeResult<Json> {
1330 let mut parser = Parser::new(s.chars());
1334 /// A structure to decode JSON to values in rust.
1335 pub struct Decoder {
1340 /// Creates a new decoder instance for decoding the specified JSON value.
1341 pub fn new(json: Json) -> Decoder {
1349 fn pop(&mut self) -> Json {
1350 self.stack.pop().unwrap()
1354 macro_rules! expect(
1355 ($e:expr, Null) => ({
1358 other => Err(ExpectedError("Null".to_owned(), format!("{}", other)))
1361 ($e:expr, $t:ident) => ({
1364 other => Err(ExpectedError(stringify!($t).to_owned(), format!("{}", other)))
1369 impl ::Decoder<Error> for Decoder {
1370 fn read_nil(&mut self) -> DecodeResult<()> {
1372 try!(expect!(self.pop(), Null));
1376 fn read_u64(&mut self) -> DecodeResult<u64 > { Ok(try!(self.read_f64()) as u64) }
1377 fn read_u32(&mut self) -> DecodeResult<u32 > { Ok(try!(self.read_f64()) as u32) }
1378 fn read_u16(&mut self) -> DecodeResult<u16 > { Ok(try!(self.read_f64()) as u16) }
1379 fn read_u8 (&mut self) -> DecodeResult<u8 > { Ok(try!(self.read_f64()) as u8) }
1380 fn read_uint(&mut self) -> DecodeResult<uint> { Ok(try!(self.read_f64()) as uint) }
1382 fn read_i64(&mut self) -> DecodeResult<i64> { Ok(try!(self.read_f64()) as i64) }
1383 fn read_i32(&mut self) -> DecodeResult<i32> { Ok(try!(self.read_f64()) as i32) }
1384 fn read_i16(&mut self) -> DecodeResult<i16> { Ok(try!(self.read_f64()) as i16) }
1385 fn read_i8 (&mut self) -> DecodeResult<i8 > { Ok(try!(self.read_f64()) as i8) }
1386 fn read_int(&mut self) -> DecodeResult<int> { Ok(try!(self.read_f64()) as int) }
1388 fn read_bool(&mut self) -> DecodeResult<bool> {
1389 debug!("read_bool");
1390 Ok(try!(expect!(self.pop(), Boolean)))
1393 fn read_f64(&mut self) -> DecodeResult<f64> {
1394 use std::from_str::FromStr;
1399 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
1400 // is going to have a string here, as per JSON spec..
1401 Ok(FromStr::from_str(s).unwrap())
1403 value => Err(ExpectedError("Number".to_owned(), format!("{}", value)))
1407 fn read_f32(&mut self) -> DecodeResult<f32> { Ok(try!(self.read_f64()) as f32) }
1409 fn read_char(&mut self) -> DecodeResult<char> {
1410 let s = try!(self.read_str());
1412 let mut it = s.chars();
1413 match (it.next(), it.next()) {
1414 // exactly one character
1415 (Some(c), None) => return Ok(c),
1419 Err(ExpectedError("single character string".to_owned(), format!("{}", s)))
1422 fn read_str(&mut self) -> DecodeResult<~str> {
1424 Ok(try!(expect!(self.pop(), String)))
1427 fn read_enum<T>(&mut self,
1429 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
1430 debug!("read_enum({})", name);
1434 fn read_enum_variant<T>(&mut self,
1436 f: |&mut Decoder, uint| -> DecodeResult<T>)
1437 -> DecodeResult<T> {
1438 debug!("read_enum_variant(names={:?})", names);
1439 let name = match self.pop() {
1442 let n = match o.pop(&"variant".to_owned()) {
1443 Some(String(s)) => s,
1444 Some(val) => return Err(ExpectedError("String".to_owned(), format!("{}", val))),
1445 None => return Err(MissingFieldError("variant".to_owned()))
1447 match o.pop(&"fields".to_owned()) {
1449 for field in l.move_rev_iter() {
1450 self.stack.push(field.clone());
1453 Some(val) => return Err(ExpectedError("List".to_owned(), format!("{}", val))),
1454 None => return Err(MissingFieldError("fields".to_owned()))
1458 json => return Err(ExpectedError("String or Object".to_owned(), format!("{}", json)))
1460 let idx = match names.iter().position(|n| str::eq_slice(*n, name)) {
1462 None => return Err(UnknownVariantError(name))
1467 fn read_enum_variant_arg<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
1468 -> DecodeResult<T> {
1469 debug!("read_enum_variant_arg(idx={})", idx);
1473 fn read_enum_struct_variant<T>(&mut self,
1475 f: |&mut Decoder, uint| -> DecodeResult<T>)
1476 -> DecodeResult<T> {
1477 debug!("read_enum_struct_variant(names={:?})", names);
1478 self.read_enum_variant(names, f)
1482 fn read_enum_struct_variant_field<T>(&mut self,
1485 f: |&mut Decoder| -> DecodeResult<T>)
1486 -> DecodeResult<T> {
1487 debug!("read_enum_struct_variant_field(name={}, idx={})", name, idx);
1488 self.read_enum_variant_arg(idx, f)
1491 fn read_struct<T>(&mut self,
1494 f: |&mut Decoder| -> DecodeResult<T>)
1495 -> DecodeResult<T> {
1496 debug!("read_struct(name={}, len={})", name, len);
1497 let value = try!(f(self));
1502 fn read_struct_field<T>(&mut self,
1505 f: |&mut Decoder| -> DecodeResult<T>)
1506 -> DecodeResult<T> {
1507 debug!("read_struct_field(name={}, idx={})", name, idx);
1508 let mut obj = try!(expect!(self.pop(), Object));
1510 let value = match obj.pop(&name.to_owned()) {
1511 None => return Err(MissingFieldError(name.to_owned())),
1513 self.stack.push(json);
1517 self.stack.push(Object(obj));
1521 fn read_tuple<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
1522 debug!("read_tuple()");
1526 fn read_tuple_arg<T>(&mut self,
1528 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
1529 debug!("read_tuple_arg(idx={})", idx);
1530 self.read_seq_elt(idx, f)
1533 fn read_tuple_struct<T>(&mut self,
1535 f: |&mut Decoder, uint| -> DecodeResult<T>)
1536 -> DecodeResult<T> {
1537 debug!("read_tuple_struct(name={})", name);
1541 fn read_tuple_struct_arg<T>(&mut self,
1543 f: |&mut Decoder| -> DecodeResult<T>)
1544 -> DecodeResult<T> {
1545 debug!("read_tuple_struct_arg(idx={})", idx);
1546 self.read_tuple_arg(idx, f)
1549 fn read_option<T>(&mut self, f: |&mut Decoder, bool| -> DecodeResult<T>) -> DecodeResult<T> {
1551 Null => f(self, false),
1552 value => { self.stack.push(value); f(self, true) }
1556 fn read_seq<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
1557 debug!("read_seq()");
1558 let list = try!(expect!(self.pop(), List));
1559 let len = list.len();
1560 for v in list.move_rev_iter() {
1566 fn read_seq_elt<T>(&mut self,
1568 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
1569 debug!("read_seq_elt(idx={})", idx);
1573 fn read_map<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
1574 debug!("read_map()");
1575 let obj = try!(expect!(self.pop(), Object));
1576 let len = obj.len();
1577 for (key, value) in obj.move_iter() {
1578 self.stack.push(value);
1579 self.stack.push(String(key));
1584 fn read_map_elt_key<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
1585 -> DecodeResult<T> {
1586 debug!("read_map_elt_key(idx={})", idx);
1590 fn read_map_elt_val<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
1591 -> DecodeResult<T> {
1592 debug!("read_map_elt_val(idx={})", idx);
1597 /// Test if two json values are less than one another
1599 fn lt(&self, other: &Json) -> bool {
1603 Number(f1) => f0 < f1,
1604 String(_) | Boolean(_) | List(_) | Object(_) |
1612 String(ref s1) => s0 < s1,
1613 Boolean(_) | List(_) | Object(_) | Null => true
1619 Number(_) | String(_) => false,
1620 Boolean(b1) => b0 < b1,
1621 List(_) | Object(_) | Null => true
1627 Number(_) | String(_) | Boolean(_) => false,
1628 List(ref l1) => (*l0) < (*l1),
1629 Object(_) | Null => true
1635 Number(_) | String(_) | Boolean(_) | List(_) => false,
1636 Object(ref d1) => d0 < d1,
1643 Number(_) | String(_) | Boolean(_) | List(_) |
1653 /// A trait for converting values to JSON
1655 /// Converts the value of `self` to an instance of JSON
1656 fn to_json(&self) -> Json;
1659 impl ToJson for Json {
1660 fn to_json(&self) -> Json { (*self).clone() }
1663 impl ToJson for int {
1664 fn to_json(&self) -> Json { Number(*self as f64) }
1667 impl ToJson for i8 {
1668 fn to_json(&self) -> Json { Number(*self as f64) }
1671 impl ToJson for i16 {
1672 fn to_json(&self) -> Json { Number(*self as f64) }
1675 impl ToJson for i32 {
1676 fn to_json(&self) -> Json { Number(*self as f64) }
1679 impl ToJson for i64 {
1680 fn to_json(&self) -> Json { Number(*self as f64) }
1683 impl ToJson for uint {
1684 fn to_json(&self) -> Json { Number(*self as f64) }
1687 impl ToJson for u8 {
1688 fn to_json(&self) -> Json { Number(*self as f64) }
1691 impl ToJson for u16 {
1692 fn to_json(&self) -> Json { Number(*self as f64) }
1695 impl ToJson for u32 {
1696 fn to_json(&self) -> Json { Number(*self as f64) }
1699 impl ToJson for u64 {
1700 fn to_json(&self) -> Json { Number(*self as f64) }
1703 impl ToJson for f32 {
1704 fn to_json(&self) -> Json { Number(*self as f64) }
1707 impl ToJson for f64 {
1708 fn to_json(&self) -> Json { Number(*self) }
1711 impl ToJson for () {
1712 fn to_json(&self) -> Json { Null }
1715 impl ToJson for bool {
1716 fn to_json(&self) -> Json { Boolean(*self) }
1719 impl ToJson for ~str {
1720 fn to_json(&self) -> Json { String((*self).clone()) }
1723 impl<A:ToJson,B:ToJson> ToJson for (A, B) {
1724 fn to_json(&self) -> Json {
1727 List(~[a.to_json(), b.to_json()])
1733 impl<A:ToJson,B:ToJson,C:ToJson> ToJson for (A, B, C) {
1734 fn to_json(&self) -> Json {
1736 (ref a, ref b, ref c) => {
1737 List(~[a.to_json(), b.to_json(), c.to_json()])
1743 impl<A:ToJson> ToJson for ~[A] {
1744 fn to_json(&self) -> Json { List(self.iter().map(|elt| elt.to_json()).collect()) }
1747 impl<A:ToJson> ToJson for TreeMap<~str, A> {
1748 fn to_json(&self) -> Json {
1749 let mut d = TreeMap::new();
1750 for (key, value) in self.iter() {
1751 d.insert((*key).clone(), value.to_json());
1757 impl<A:ToJson> ToJson for HashMap<~str, A> {
1758 fn to_json(&self) -> Json {
1759 let mut d = TreeMap::new();
1760 for (key, value) in self.iter() {
1761 d.insert((*key).clone(), value.to_json());
1767 impl<A:ToJson> ToJson for Option<A> {
1768 fn to_json(&self) -> Json {
1771 Some(ref value) => value.to_json()
1776 impl fmt::Show for Json {
1777 /// Encodes a json value into a string
1778 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1779 self.to_writer(f.buf)
1785 use {Encodable, Decodable};
1786 use super::{Encoder, Decoder, Error, Boolean, Number, List, String, Null,
1787 PrettyEncoder, Object, Json, from_str, ParseError, ExpectedError,
1788 MissingFieldError, UnknownVariantError, DecodeResult };
1790 use collections::TreeMap;
1792 #[deriving(Eq, Encodable, Decodable, Show)]
1798 #[deriving(Eq, Encodable, Decodable, Show)]
1805 #[deriving(Eq, Encodable, Decodable, Show)]
1810 fn mk_object(items: &[(~str, Json)]) -> Json {
1811 let mut d = ~TreeMap::new();
1813 for item in items.iter() {
1815 (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
1823 fn test_write_null() {
1824 assert_eq!(Null.to_str(), "null".to_owned());
1825 assert_eq!(Null.to_pretty_str(), "null".to_owned());
1830 fn test_write_number() {
1831 assert_eq!(Number(3.0).to_str(), "3".to_owned());
1832 assert_eq!(Number(3.0).to_pretty_str(), "3".to_owned());
1834 assert_eq!(Number(3.1).to_str(), "3.1".to_owned());
1835 assert_eq!(Number(3.1).to_pretty_str(), "3.1".to_owned());
1837 assert_eq!(Number(-1.5).to_str(), "-1.5".to_owned());
1838 assert_eq!(Number(-1.5).to_pretty_str(), "-1.5".to_owned());
1840 assert_eq!(Number(0.5).to_str(), "0.5".to_owned());
1841 assert_eq!(Number(0.5).to_pretty_str(), "0.5".to_owned());
1845 fn test_write_str() {
1846 assert_eq!(String("".to_owned()).to_str(), "\"\"".to_owned());
1847 assert_eq!(String("".to_owned()).to_pretty_str(), "\"\"".to_owned());
1849 assert_eq!(String("foo".to_owned()).to_str(), "\"foo\"".to_owned());
1850 assert_eq!(String("foo".to_owned()).to_pretty_str(), "\"foo\"".to_owned());
1854 fn test_write_bool() {
1855 assert_eq!(Boolean(true).to_str(), "true".to_owned());
1856 assert_eq!(Boolean(true).to_pretty_str(), "true".to_owned());
1858 assert_eq!(Boolean(false).to_str(), "false".to_owned());
1859 assert_eq!(Boolean(false).to_pretty_str(), "false".to_owned());
1863 fn test_write_list() {
1864 assert_eq!(List(~[]).to_str(), "[]".to_owned());
1865 assert_eq!(List(~[]).to_pretty_str(), "[]".to_owned());
1867 assert_eq!(List(~[Boolean(true)]).to_str(), "[true]".to_owned());
1869 List(~[Boolean(true)]).to_pretty_str(),
1876 let long_test_list = List(~[
1879 List(~[String("foo\nbar".to_owned()), Number(3.5)])]);
1881 assert_eq!(long_test_list.to_str(),
1882 "[false,null,[\"foo\\nbar\",3.5]]".to_owned());
1884 long_test_list.to_pretty_str(),
1898 fn test_write_object() {
1899 assert_eq!(mk_object([]).to_str(), "{}".to_owned());
1900 assert_eq!(mk_object([]).to_pretty_str(), "{}".to_owned());
1903 mk_object([("a".to_owned(), Boolean(true))]).to_str(),
1904 "{\"a\":true}".to_owned()
1907 mk_object([("a".to_owned(), Boolean(true))]).to_pretty_str(),
1914 let complex_obj = mk_object([
1915 ("b".to_owned(), List(~[
1916 mk_object([("c".to_owned(), String("\x0c\r".to_owned()))]),
1917 mk_object([("d".to_owned(), String("".to_owned()))])
1922 complex_obj.to_str(),
1925 {\"c\":\"\\f\\r\"},\
1931 complex_obj.to_pretty_str(),
1936 \"c\": \"\\f\\r\"\n \
1946 ("a".to_owned(), Boolean(true)),
1947 ("b".to_owned(), List(~[
1948 mk_object([("c".to_owned(), String("\x0c\r".to_owned()))]),
1949 mk_object([("d".to_owned(), String("".to_owned()))])
1953 // We can't compare the strings directly because the object fields be
1954 // printed in a different order.
1955 assert_eq!(a.clone(), from_str(a.to_str()).unwrap());
1956 assert_eq!(a.clone(), from_str(a.to_pretty_str()).unwrap());
1959 fn with_str_writer(f: |&mut io::Writer|) -> ~str {
1960 use std::io::MemWriter;
1963 let mut m = MemWriter::new();
1964 f(&mut m as &mut io::Writer);
1965 str::from_utf8(m.unwrap().as_slice()).unwrap().to_owned()
1969 fn test_write_enum() {
1972 with_str_writer(|wr| {
1973 let mut encoder = Encoder::new(wr);
1974 animal.encode(&mut encoder).unwrap();
1976 "\"Dog\"".to_owned()
1979 with_str_writer(|wr| {
1980 let mut encoder = PrettyEncoder::new(wr);
1981 animal.encode(&mut encoder).unwrap();
1983 "\"Dog\"".to_owned()
1986 let animal = Frog("Henry".to_owned(), 349);
1988 with_str_writer(|wr| {
1989 let mut encoder = Encoder::new(wr);
1990 animal.encode(&mut encoder).unwrap();
1992 "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}".to_owned()
1995 with_str_writer(|wr| {
1996 let mut encoder = PrettyEncoder::new(wr);
1997 animal.encode(&mut encoder).unwrap();
2009 fn test_write_some() {
2010 let value = Some("jodhpurs".to_owned());
2011 let s = with_str_writer(|wr| {
2012 let mut encoder = Encoder::new(wr);
2013 value.encode(&mut encoder).unwrap();
2015 assert_eq!(s, "\"jodhpurs\"".to_owned());
2017 let value = Some("jodhpurs".to_owned());
2018 let s = with_str_writer(|wr| {
2019 let mut encoder = PrettyEncoder::new(wr);
2020 value.encode(&mut encoder).unwrap();
2022 assert_eq!(s, "\"jodhpurs\"".to_owned());
2026 fn test_write_none() {
2027 let value: Option<~str> = None;
2028 let s = with_str_writer(|wr| {
2029 let mut encoder = Encoder::new(wr);
2030 value.encode(&mut encoder).unwrap();
2032 assert_eq!(s, "null".to_owned());
2034 let s = with_str_writer(|wr| {
2035 let mut encoder = Encoder::new(wr);
2036 value.encode(&mut encoder).unwrap();
2038 assert_eq!(s, "null".to_owned());
2042 fn test_trailing_characters() {
2043 assert_eq!(from_str("nulla"),
2044 Err(ParseError("trailing characters".to_owned(), 1u, 5u)));
2045 assert_eq!(from_str("truea"),
2046 Err(ParseError("trailing characters".to_owned(), 1u, 5u)));
2047 assert_eq!(from_str("falsea"),
2048 Err(ParseError("trailing characters".to_owned(), 1u, 6u)));
2049 assert_eq!(from_str("1a"),
2050 Err(ParseError("trailing characters".to_owned(), 1u, 2u)));
2051 assert_eq!(from_str("[]a"),
2052 Err(ParseError("trailing characters".to_owned(), 1u, 3u)));
2053 assert_eq!(from_str("{}a"),
2054 Err(ParseError("trailing characters".to_owned(), 1u, 3u)));
2058 fn test_read_identifiers() {
2059 assert_eq!(from_str("n"),
2060 Err(ParseError("invalid syntax".to_owned(), 1u, 2u)));
2061 assert_eq!(from_str("nul"),
2062 Err(ParseError("invalid syntax".to_owned(), 1u, 4u)));
2064 assert_eq!(from_str("t"),
2065 Err(ParseError("invalid syntax".to_owned(), 1u, 2u)));
2066 assert_eq!(from_str("truz"),
2067 Err(ParseError("invalid syntax".to_owned(), 1u, 4u)));
2069 assert_eq!(from_str("f"),
2070 Err(ParseError("invalid syntax".to_owned(), 1u, 2u)));
2071 assert_eq!(from_str("faz"),
2072 Err(ParseError("invalid syntax".to_owned(), 1u, 3u)));
2074 assert_eq!(from_str("null"), Ok(Null));
2075 assert_eq!(from_str("true"), Ok(Boolean(true)));
2076 assert_eq!(from_str("false"), Ok(Boolean(false)));
2077 assert_eq!(from_str(" null "), Ok(Null));
2078 assert_eq!(from_str(" true "), Ok(Boolean(true)));
2079 assert_eq!(from_str(" false "), Ok(Boolean(false)));
2083 fn test_decode_identifiers() {
2084 let mut decoder = Decoder::new(from_str("null").unwrap());
2085 let v: () = Decodable::decode(&mut decoder).unwrap();
2088 let mut decoder = Decoder::new(from_str("true").unwrap());
2089 let v: bool = Decodable::decode(&mut decoder).unwrap();
2090 assert_eq!(v, true);
2092 let mut decoder = Decoder::new(from_str("false").unwrap());
2093 let v: bool = Decodable::decode(&mut decoder).unwrap();
2094 assert_eq!(v, false);
2098 fn test_read_number() {
2099 assert_eq!(from_str("+"),
2100 Err(ParseError("invalid syntax".to_owned(), 1u, 1u)));
2101 assert_eq!(from_str("."),
2102 Err(ParseError("invalid syntax".to_owned(), 1u, 1u)));
2104 assert_eq!(from_str("-"),
2105 Err(ParseError("invalid number".to_owned(), 1u, 2u)));
2106 assert_eq!(from_str("00"),
2107 Err(ParseError("invalid number".to_owned(), 1u, 2u)));
2108 assert_eq!(from_str("1."),
2109 Err(ParseError("invalid number".to_owned(), 1u, 3u)));
2110 assert_eq!(from_str("1e"),
2111 Err(ParseError("invalid number".to_owned(), 1u, 3u)));
2112 assert_eq!(from_str("1e+"),
2113 Err(ParseError("invalid number".to_owned(), 1u, 4u)));
2115 assert_eq!(from_str("3"), Ok(Number(3.0)));
2116 assert_eq!(from_str("3.1"), Ok(Number(3.1)));
2117 assert_eq!(from_str("-1.2"), Ok(Number(-1.2)));
2118 assert_eq!(from_str("0.4"), Ok(Number(0.4)));
2119 assert_eq!(from_str("0.4e5"), Ok(Number(0.4e5)));
2120 assert_eq!(from_str("0.4e+15"), Ok(Number(0.4e15)));
2121 assert_eq!(from_str("0.4e-01"), Ok(Number(0.4e-01)));
2122 assert_eq!(from_str(" 3 "), Ok(Number(3.0)));
2126 fn test_decode_numbers() {
2127 let mut decoder = Decoder::new(from_str("3").unwrap());
2128 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2131 let mut decoder = Decoder::new(from_str("3.1").unwrap());
2132 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2135 let mut decoder = Decoder::new(from_str("-1.2").unwrap());
2136 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2137 assert_eq!(v, -1.2);
2139 let mut decoder = Decoder::new(from_str("0.4").unwrap());
2140 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2143 let mut decoder = Decoder::new(from_str("0.4e5").unwrap());
2144 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2145 assert_eq!(v, 0.4e5);
2147 let mut decoder = Decoder::new(from_str("0.4e15").unwrap());
2148 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2149 assert_eq!(v, 0.4e15);
2151 let mut decoder = Decoder::new(from_str("0.4e-01").unwrap());
2152 let v: f64 = Decodable::decode(&mut decoder).unwrap();
2153 assert_eq!(v, 0.4e-01);
2157 fn test_read_str() {
2158 assert_eq!(from_str("\""),
2159 Err(ParseError("EOF while parsing string".to_owned(), 1u, 2u)));
2160 assert_eq!(from_str("\"lol"),
2161 Err(ParseError("EOF while parsing string".to_owned(), 1u, 5u)));
2163 assert_eq!(from_str("\"\""), Ok(String("".to_owned())));
2164 assert_eq!(from_str("\"foo\""), Ok(String("foo".to_owned())));
2165 assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_owned())));
2166 assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_owned())));
2167 assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_owned())));
2168 assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_owned())));
2169 assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_owned())));
2170 assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_owned())));
2171 assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u12ab".to_owned())));
2172 assert_eq!(from_str("\"\\uAB12\""), Ok(String("\uAB12".to_owned())));
2174 // Non-BMP escapes. The exact error messages and positions are kind of
2176 assert_eq!(from_str("\"\\ud83d\\udca9\""), Ok(String("\U0001F4A9".to_owned())));
2177 assert!(from_str("\"\\ud83d\"").is_err());
2178 assert!(from_str("\"\\udca9\"").is_err());
2179 assert!(from_str("\"\\ud83d\\ud83d\"").is_err());
2180 assert!(from_str("\"\\ud83dx\"").is_err());
2181 assert!(from_str("\"\\udca9\\udca9\"").is_err());
2182 assert!(from_str("\"\\udca9x\"").is_err());
2186 fn test_decode_str() {
2187 let mut decoder = Decoder::new(from_str("\"\"").unwrap());
2188 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2189 assert_eq!(v, "".to_owned());
2191 let mut decoder = Decoder::new(from_str("\"foo\"").unwrap());
2192 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2193 assert_eq!(v, "foo".to_owned());
2195 let mut decoder = Decoder::new(from_str("\"\\\"\"").unwrap());
2196 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2197 assert_eq!(v, "\"".to_owned());
2199 let mut decoder = Decoder::new(from_str("\"\\b\"").unwrap());
2200 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2201 assert_eq!(v, "\x08".to_owned());
2203 let mut decoder = Decoder::new(from_str("\"\\n\"").unwrap());
2204 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2205 assert_eq!(v, "\n".to_owned());
2207 let mut decoder = Decoder::new(from_str("\"\\r\"").unwrap());
2208 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2209 assert_eq!(v, "\r".to_owned());
2211 let mut decoder = Decoder::new(from_str("\"\\t\"").unwrap());
2212 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2213 assert_eq!(v, "\t".to_owned());
2215 let mut decoder = Decoder::new(from_str("\"\\u12ab\"").unwrap());
2216 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2217 assert_eq!(v, "\u12ab".to_owned());
2219 let mut decoder = Decoder::new(from_str("\"\\uAB12\"").unwrap());
2220 let v: ~str = Decodable::decode(&mut decoder).unwrap();
2221 assert_eq!(v, "\uAB12".to_owned());
2225 fn test_read_list() {
2226 assert_eq!(from_str("["),
2227 Err(ParseError("EOF while parsing value".to_owned(), 1u, 2u)));
2228 assert_eq!(from_str("[1"),
2229 Err(ParseError("EOF while parsing list".to_owned(), 1u, 3u)));
2230 assert_eq!(from_str("[1,"),
2231 Err(ParseError("EOF while parsing value".to_owned(), 1u, 4u)));
2232 assert_eq!(from_str("[1,]"),
2233 Err(ParseError("invalid syntax".to_owned(), 1u, 4u)));
2234 assert_eq!(from_str("[6 7]"),
2235 Err(ParseError("expected `,` or `]`".to_owned(), 1u, 4u)));
2237 assert_eq!(from_str("[]"), Ok(List(~[])));
2238 assert_eq!(from_str("[ ]"), Ok(List(~[])));
2239 assert_eq!(from_str("[true]"), Ok(List(~[Boolean(true)])));
2240 assert_eq!(from_str("[ false ]"), Ok(List(~[Boolean(false)])));
2241 assert_eq!(from_str("[null]"), Ok(List(~[Null])));
2242 assert_eq!(from_str("[3, 1]"),
2243 Ok(List(~[Number(3.0), Number(1.0)])));
2244 assert_eq!(from_str("\n[3, 2]\n"),
2245 Ok(List(~[Number(3.0), Number(2.0)])));
2246 assert_eq!(from_str("[2, [4, 1]]"),
2247 Ok(List(~[Number(2.0), List(~[Number(4.0), Number(1.0)])])));
2251 fn test_decode_list() {
2252 let mut decoder = Decoder::new(from_str("[]").unwrap());
2253 let v: ~[()] = Decodable::decode(&mut decoder).unwrap();
2256 let mut decoder = Decoder::new(from_str("[null]").unwrap());
2257 let v: ~[()] = Decodable::decode(&mut decoder).unwrap();
2258 assert_eq!(v, ~[()]);
2260 let mut decoder = Decoder::new(from_str("[true]").unwrap());
2261 let v: ~[bool] = Decodable::decode(&mut decoder).unwrap();
2262 assert_eq!(v, ~[true]);
2264 let mut decoder = Decoder::new(from_str("[true]").unwrap());
2265 let v: ~[bool] = Decodable::decode(&mut decoder).unwrap();
2266 assert_eq!(v, ~[true]);
2268 let mut decoder = Decoder::new(from_str("[3, 1]").unwrap());
2269 let v: ~[int] = Decodable::decode(&mut decoder).unwrap();
2270 assert_eq!(v, ~[3, 1]);
2272 let mut decoder = Decoder::new(from_str("[[3], [1, 2]]").unwrap());
2273 let v: ~[~[uint]] = Decodable::decode(&mut decoder).unwrap();
2274 assert_eq!(v, ~[~[3], ~[1, 2]]);
2278 fn test_read_object() {
2279 assert_eq!(from_str("{"),
2280 Err(ParseError("EOF while parsing object".to_owned(), 1u, 2u)));
2281 assert_eq!(from_str("{ "),
2282 Err(ParseError("EOF while parsing object".to_owned(), 1u, 3u)));
2283 assert_eq!(from_str("{1"),
2284 Err(ParseError("key must be a string".to_owned(), 1u, 2u)));
2285 assert_eq!(from_str("{ \"a\""),
2286 Err(ParseError("EOF while parsing object".to_owned(), 1u, 6u)));
2287 assert_eq!(from_str("{\"a\""),
2288 Err(ParseError("EOF while parsing object".to_owned(), 1u, 5u)));
2289 assert_eq!(from_str("{\"a\" "),
2290 Err(ParseError("EOF while parsing object".to_owned(), 1u, 6u)));
2292 assert_eq!(from_str("{\"a\" 1"),
2293 Err(ParseError("expected `:`".to_owned(), 1u, 6u)));
2294 assert_eq!(from_str("{\"a\":"),
2295 Err(ParseError("EOF while parsing value".to_owned(), 1u, 6u)));
2296 assert_eq!(from_str("{\"a\":1"),
2297 Err(ParseError("EOF while parsing object".to_owned(), 1u, 7u)));
2298 assert_eq!(from_str("{\"a\":1 1"),
2299 Err(ParseError("expected `,` or `}`".to_owned(), 1u, 8u)));
2300 assert_eq!(from_str("{\"a\":1,"),
2301 Err(ParseError("EOF while parsing object".to_owned(), 1u, 8u)));
2303 assert_eq!(from_str("{}").unwrap(), mk_object([]));
2304 assert_eq!(from_str("{\"a\": 3}").unwrap(),
2305 mk_object([("a".to_owned(), Number(3.0))]));
2307 assert_eq!(from_str(
2308 "{ \"a\": null, \"b\" : true }").unwrap(),
2310 ("a".to_owned(), Null),
2311 ("b".to_owned(), Boolean(true))]));
2312 assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
2314 ("a".to_owned(), Null),
2315 ("b".to_owned(), Boolean(true))]));
2316 assert_eq!(from_str(
2317 "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
2319 ("a".to_owned(), Number(1.0)),
2320 ("b".to_owned(), List(~[Boolean(true)]))
2322 assert_eq!(from_str(
2328 "{ \"c\": {\"d\": null} } " +
2332 ("a".to_owned(), Number(1.0)),
2333 ("b".to_owned(), List(~[
2335 String("foo\nbar".to_owned()),
2337 ("c".to_owned(), mk_object([("d".to_owned(), Null)]))
2344 fn test_decode_struct() {
2347 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
2350 let mut decoder = Decoder::new(from_str(s).unwrap());
2351 let v: Outer = Decodable::decode(&mut decoder).unwrap();
2356 Inner { a: (), b: 2, c: ~["abc".to_owned(), "xyz".to_owned()] }
2363 fn test_decode_option() {
2364 let mut decoder = Decoder::new(from_str("null").unwrap());
2365 let value: Option<~str> = Decodable::decode(&mut decoder).unwrap();
2366 assert_eq!(value, None);
2368 let mut decoder = Decoder::new(from_str("\"jodhpurs\"").unwrap());
2369 let value: Option<~str> = Decodable::decode(&mut decoder).unwrap();
2370 assert_eq!(value, Some("jodhpurs".to_owned()));
2374 fn test_decode_enum() {
2375 let mut decoder = Decoder::new(from_str("\"Dog\"").unwrap());
2376 let value: Animal = Decodable::decode(&mut decoder).unwrap();
2377 assert_eq!(value, Dog);
2379 let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
2380 let mut decoder = Decoder::new(from_str(s).unwrap());
2381 let value: Animal = Decodable::decode(&mut decoder).unwrap();
2382 assert_eq!(value, Frog("Henry".to_owned(), 349));
2386 fn test_decode_map() {
2387 let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
2388 \"fields\":[\"Henry\", 349]}}".to_owned();
2389 let mut decoder = Decoder::new(from_str(s).unwrap());
2390 let mut map: TreeMap<~str, Animal> = Decodable::decode(&mut decoder).unwrap();
2392 assert_eq!(map.pop(&"a".to_owned()), Some(Dog));
2393 assert_eq!(map.pop(&"b".to_owned()), Some(Frog("Henry".to_owned(), 349)));
2397 fn test_multiline_errors() {
2398 assert_eq!(from_str("{\n \"foo\":\n \"bar\""),
2399 Err(ParseError("EOF while parsing object".to_owned(), 3u, 8u)));
2402 #[deriving(Decodable)]
2403 struct DecodeStruct {
2409 #[deriving(Decodable)]
2414 fn check_err<T: Decodable<Decoder, Error>>(to_parse: &'static str, expected: Error) {
2415 let res: DecodeResult<T> = match from_str(to_parse) {
2417 Ok(json) => Decodable::decode(&mut Decoder::new(json))
2420 Ok(_) => fail!("`{}` parsed & decoded ok, expecting error `{}`",
2421 to_parse, expected),
2422 Err(ParseError(e, _, _)) => fail!("`{}` is not valid json: {}",
2425 assert_eq!(e, expected);
2431 fn test_decode_errors_struct() {
2432 check_err::<DecodeStruct>("[]", ExpectedError("Object".to_owned(), "[]".to_owned()));
2433 check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
2434 ExpectedError("Number".to_owned(), "true".to_owned()));
2435 check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
2436 ExpectedError("Boolean".to_owned(), "[]".to_owned()));
2437 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
2438 ExpectedError("String".to_owned(), "{}".to_owned()));
2439 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
2440 ExpectedError("List".to_owned(), "null".to_owned()));
2441 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
2442 MissingFieldError("w".to_owned()));
2445 fn test_decode_errors_enum() {
2446 check_err::<DecodeEnum>("{}",
2447 MissingFieldError("variant".to_owned()));
2448 check_err::<DecodeEnum>("{\"variant\": 1}",
2449 ExpectedError("String".to_owned(), "1".to_owned()));
2450 check_err::<DecodeEnum>("{\"variant\": \"A\"}",
2451 MissingFieldError("fields".to_owned()));
2452 check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
2453 ExpectedError("List".to_owned(), "null".to_owned()));
2454 check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
2455 UnknownVariantError("C".to_owned()));
2460 let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
2461 let found_str = json_value.find(&"dog".to_owned());
2462 assert!(found_str.is_some() && found_str.unwrap().as_string().unwrap() == &"cat");
2466 fn test_find_path(){
2467 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
2468 let found_str = json_value.find_path(&[&"dog".to_owned(),
2469 &"cat".to_owned(), &"mouse".to_owned()]);
2470 assert!(found_str.is_some() && found_str.unwrap().as_string().unwrap() == &"cheese");
2475 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
2476 let found_str = json_value.search(&"mouse".to_owned()).and_then(|j| j.as_string());
2477 assert!(found_str.is_some());
2478 assert!(found_str.unwrap() == &"cheese");
2482 fn test_is_object(){
2483 let json_value = from_str("{}").unwrap();
2484 assert!(json_value.is_object());
2488 fn test_as_object(){
2489 let json_value = from_str("{}").unwrap();
2490 let json_object = json_value.as_object();
2491 assert!(json_object.is_some());
2496 let json_value = from_str("[1, 2, 3]").unwrap();
2497 assert!(json_value.is_list());
2502 let json_value = from_str("[1, 2, 3]").unwrap();
2503 let json_list = json_value.as_list();
2504 let expected_length = 3;
2505 assert!(json_list.is_some() && json_list.unwrap().len() == expected_length);
2509 fn test_is_string(){
2510 let json_value = from_str("\"dog\"").unwrap();
2511 assert!(json_value.is_string());
2515 fn test_as_string(){
2516 let json_value = from_str("\"dog\"").unwrap();
2517 let json_str = json_value.as_string();
2518 let expected_str = &"dog";
2519 assert_eq!(json_str, Some(expected_str));
2523 fn test_is_number(){
2524 let json_value = from_str("12").unwrap();
2525 assert!(json_value.is_number());
2529 fn test_as_number(){
2530 let json_value = from_str("12").unwrap();
2531 let json_num = json_value.as_number();
2532 let expected_num = 12f64;
2533 assert!(json_num.is_some() && json_num.unwrap() == expected_num);
2537 fn test_is_boolean(){
2538 let json_value = from_str("false").unwrap();
2539 assert!(json_value.is_boolean());
2543 fn test_as_boolean(){
2544 let json_value = from_str("false").unwrap();
2545 let json_bool = json_value.as_boolean();
2546 let expected_bool = false;
2547 assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
2552 let json_value = from_str("null").unwrap();
2553 assert!(json_value.is_null());
2558 let json_value = from_str("null").unwrap();
2559 let json_null = json_value.as_null();
2560 let expected_null = ();
2561 assert!(json_null.is_some() && json_null.unwrap() == expected_null);
2565 fn test_encode_hashmap_with_numeric_key() {
2566 use std::str::from_utf8;
2567 use std::io::Writer;
2568 use std::io::MemWriter;
2569 use collections::HashMap;
2570 let mut hm: HashMap<uint, bool> = HashMap::new();
2572 let mut mem_buf = MemWriter::new();
2574 let mut encoder = Encoder::new(&mut mem_buf as &mut io::Writer);
2575 hm.encode(&mut encoder).unwrap();
2577 let bytes = mem_buf.unwrap();
2578 let json_str = from_utf8(bytes.as_slice()).unwrap();
2579 match from_str(json_str) {
2580 Err(_) => fail!("Unable to parse json_str: {:?}", json_str),
2581 _ => {} // it parsed and we are good to go
2585 fn test_prettyencode_hashmap_with_numeric_key() {
2586 use std::str::from_utf8;
2587 use std::io::Writer;
2588 use std::io::MemWriter;
2589 use collections::HashMap;
2590 let mut hm: HashMap<uint, bool> = HashMap::new();
2592 let mut mem_buf = MemWriter::new();
2594 let mut encoder = PrettyEncoder::new(&mut mem_buf as &mut io::Writer);
2595 hm.encode(&mut encoder).unwrap();
2597 let bytes = mem_buf.unwrap();
2598 let json_str = from_utf8(bytes.as_slice()).unwrap();
2599 match from_str(json_str) {
2600 Err(_) => fail!("Unable to parse json_str: {:?}", json_str),
2601 _ => {} // it parsed and we are good to go
2605 fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
2606 use collections::HashMap;
2608 let json_str = "{\"1\":true}";
2609 let json_obj = match from_str(json_str) {
2610 Err(_) => fail!("Unable to parse json_str: {:?}", json_str),
2613 let mut decoder = Decoder::new(json_obj);
2614 let _hm: HashMap<uint, bool> = Decodable::decode(&mut decoder).unwrap();