1 // Copyright 2012-2014 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 to encode structured data in a text format that can be easily read by humans.
24 Its simple syntax and native compatibility with JavaScript have made it a widely used format.
26 Data types that can be encoded are JavaScript types (see the `Json` enum for more details):
28 * `Boolean`: equivalent to rust's `bool`
29 * `Number`: equivalent to rust's `f64`
30 * `String`: equivalent to rust's `String`
31 * `Array`: equivalent to rust's `Vec<T>`, but also allowing objects of different types in the same
33 * `Object`: equivalent to rust's `Treemap<String, json::Json>`
36 An object is a series of string keys mapping to values, in `"key": value` format.
37 Arrays are enclosed in square brackets ([ ... ]) and objects in curly brackets ({ ... }).
38 A simple JSON document encoding a person, his/her age, address and phone numbers could look like:
46 "Street": "Downing Street 10",
48 "Country": "Great Britain"
57 # Rust Type-based Encoding and Decoding
59 Rust provides a mechanism for low boilerplate encoding & decoding of values to and from JSON via
60 the serialization API.
61 To be able to encode a piece of data, it must implement the `serialize::Encodable` trait.
62 To be able to decode a piece of data, it must implement the `serialize::Decodable` trait.
63 The Rust compiler provides an annotation to automatically generate the code for these traits:
64 `#[deriving(Decodable, Encodable)]`
66 The JSON API provides an enum `json::Json` and a trait `ToJson` to encode objects.
67 The `ToJson` trait provides a `to_json` method to convert an object into a `json::Json` value.
68 A `json::Json` value can be encoded as a string or buffer using the functions described above.
69 You can also use the `json::Encoder` object, which implements the `Encoder` trait.
71 When using `ToJson` the `Encodable` trait implementation is not mandatory.
75 ## Using Autoserialization
77 Create a struct called TestStruct1 and serialize and deserialize it to and from JSON
78 using the serialization API, using the derived serialization code.
81 extern crate serialize;
84 #[deriving(Decodable, Encodable)] //generate Decodable, Encodable impl.
85 pub struct TestStruct1 {
92 let object = TestStruct1
93 {data_int: 1, data_str:"toto".to_string(), data_vector:vec![2,3,4,5]};
95 // Serialize using `json::encode`
96 let encoded = json::encode(&object);
98 // Deserialize using `json::decode`
99 let decoded: TestStruct1 = json::decode(encoded.as_slice()).unwrap();
105 This example uses the `ToJson` trait to generate the JSON string.
108 use std::collections::TreeMap;
109 use serialize::json::ToJson;
112 #[deriving(Decodable)]
113 pub struct TestStruct1 {
116 data_vector: Vec<u8>,
119 impl ToJson for TestStruct1 {
120 fn to_json( &self ) -> json::Json {
121 let mut d = TreeMap::new();
122 d.insert("data_int".to_string(), self.data_int.to_json());
123 d.insert("data_str".to_string(), self.data_str.to_json());
124 d.insert("data_vector".to_string(), self.data_vector.to_json());
130 // Serialize using `ToJson`
131 let test2 = TestStruct1 {data_int: 1, data_str:"toto".to_string(), data_vector:vec![2,3,4,5]};
132 let tjson: json::Json = test2.to_json();
133 let json_str: String = tjson.to_str();
135 // Deserialize like before
136 let decoded: TestStruct1 = json::decode(json_str.as_slice()).unwrap();
143 use std::collections::{HashMap, TreeMap};
144 use std::{char, f64, fmt, io, num, str};
145 use std::io::MemWriter;
146 use std::mem::{swap, transmute};
147 use std::num::{FPNaN, FPInfinite};
148 use std::str::ScalarValue;
149 use std::string::String;
154 /// Represents a json value
155 #[deriving(Clone, PartialEq, PartialOrd)]
165 pub type List = Vec<Json>;
166 pub type Object = TreeMap<String, Json>;
168 /// The errors that can arise while parsing a JSON stream.
169 #[deriving(Clone, PartialEq)]
173 EOFWhileParsingObject,
175 EOFWhileParsingValue,
176 EOFWhileParsingString,
181 InvalidUnicodeCodePoint,
182 LoneLeadingSurrogateInHexEscape,
183 UnexpectedEndOfHexEscape,
189 #[deriving(Clone, PartialEq, Show)]
190 pub enum ParserError {
192 SyntaxError(ErrorCode, uint, uint),
193 IoError(io::IoErrorKind, &'static str),
196 // Builder and Parser have the same errors.
197 pub type BuilderError = ParserError;
199 #[deriving(Clone, PartialEq, Show)]
200 pub enum DecoderError {
201 ParseError(ParserError),
202 ExpectedError(String, String),
203 MissingFieldError(String),
204 UnknownVariantError(String),
207 /// Returns a readable error string for a given error code.
208 pub fn error_str(error: ErrorCode) -> &'static str {
210 InvalidSyntax => "invalid syntax",
211 InvalidNumber => "invalid number",
212 EOFWhileParsingObject => "EOF While parsing object",
213 EOFWhileParsingList => "EOF While parsing list",
214 EOFWhileParsingValue => "EOF While parsing value",
215 EOFWhileParsingString => "EOF While parsing string",
216 KeyMustBeAString => "key must be a string",
217 ExpectedColon => "expected `:`",
218 TrailingCharacters => "trailing characters",
219 InvalidEscape => "invalid escape",
220 UnrecognizedHex => "invalid \\u escape (unrecognized hex)",
221 NotFourDigit => "invalid \\u escape (not four digits)",
222 NotUtf8 => "contents not utf-8",
223 InvalidUnicodeCodePoint => "invalid unicode code point",
224 LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
225 UnexpectedEndOfHexEscape => "unexpected end of hex escape",
229 /// Shortcut function to decode a JSON `&str` into an object
230 pub fn decode<T: ::Decodable<Decoder, DecoderError>>(s: &str) -> DecodeResult<T> {
231 let json = match from_str(s) {
233 Err(e) => return Err(ParseError(e))
236 let mut decoder = Decoder::new(json);
237 ::Decodable::decode(&mut decoder)
240 /// Shortcut function to encode a `T` into a JSON `String`
241 pub fn encode<'a, T: Encodable<Encoder<'a>, io::IoError>>(object: &T) -> String {
242 let buff = Encoder::buffer_encode(object);
243 str::from_utf8_owned(buff).unwrap()
246 impl fmt::Show for ErrorCode {
247 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
248 error_str(*self).fmt(f)
252 fn io_error_to_error(io: io::IoError) -> ParserError {
253 IoError(io.kind, io.desc)
256 pub type EncodeResult = io::IoResult<()>;
257 pub type DecodeResult<T> = Result<T, DecoderError>;
259 pub fn escape_bytes(wr: &mut io::Writer, bytes: &[u8]) -> Result<(), io::IoError> {
260 try!(wr.write_str("\""));
264 for (i, byte) in bytes.iter().enumerate() {
265 let escaped = match *byte {
277 try!(wr.write(bytes.slice(start, i)));
280 try!(wr.write_str(escaped));
285 if start != bytes.len() {
286 try!(wr.write(bytes.slice_from(start)));
292 fn escape_str(writer: &mut io::Writer, v: &str) -> Result<(), io::IoError> {
293 escape_bytes(writer, v.as_bytes())
296 fn escape_char(writer: &mut io::Writer, v: char) -> Result<(), io::IoError> {
297 let mut buf = [0, .. 4];
299 escape_bytes(writer, buf)
302 fn spaces(wr: &mut io::Writer, mut n: uint) -> Result<(), io::IoError> {
303 static len: uint = 16;
304 static buf: [u8, ..len] = [b' ', ..len];
312 wr.write(buf.slice_to(n))
318 fn fmt_number_or_null(v: f64) -> String {
320 FPNaN | FPInfinite => String::from_str("null"),
321 _ => f64::to_str_digits(v, 6u)
325 /// A structure for implementing serialization to JSON.
326 pub struct Encoder<'a> {
327 writer: &'a mut io::Writer,
330 impl<'a> Encoder<'a> {
331 /// Creates a new JSON encoder whose output will be written to the writer
333 pub fn new(writer: &'a mut io::Writer) -> Encoder<'a> {
334 Encoder { writer: writer }
337 /// Encode the specified struct into a json [u8]
338 pub fn buffer_encode<T:Encodable<Encoder<'a>, io::IoError>>(object: &T) -> Vec<u8> {
339 //Serialize the object in a string using a writer
340 let mut m = MemWriter::new();
341 // FIXME(14302) remove the transmute and unsafe block.
343 let mut encoder = Encoder::new(&mut m as &mut io::Writer);
344 // MemWriter never Errs
345 let _ = object.encode(transmute(&mut encoder));
350 /// Encode the specified struct into a json str
352 /// Note: this function is deprecated. Consider using `json::encode` instead.
353 #[deprecated = "Replaced by `json::encode`"]
354 pub fn str_encode<T: Encodable<Encoder<'a>, io::IoError>>(object: &T) -> String {
359 impl<'a> ::Encoder<io::IoError> for Encoder<'a> {
360 fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
362 fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) }
363 fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) }
364 fn emit_u32(&mut self, v: u32) -> EncodeResult { self.emit_f64(v as f64) }
365 fn emit_u16(&mut self, v: u16) -> EncodeResult { self.emit_f64(v as f64) }
366 fn emit_u8(&mut self, v: u8) -> EncodeResult { self.emit_f64(v as f64) }
368 fn emit_int(&mut self, v: int) -> EncodeResult { self.emit_f64(v as f64) }
369 fn emit_i64(&mut self, v: i64) -> EncodeResult { self.emit_f64(v as f64) }
370 fn emit_i32(&mut self, v: i32) -> EncodeResult { self.emit_f64(v as f64) }
371 fn emit_i16(&mut self, v: i16) -> EncodeResult { self.emit_f64(v as f64) }
372 fn emit_i8(&mut self, v: i8) -> EncodeResult { self.emit_f64(v as f64) }
374 fn emit_bool(&mut self, v: bool) -> EncodeResult {
376 write!(self.writer, "true")
378 write!(self.writer, "false")
382 fn emit_f64(&mut self, v: f64) -> EncodeResult {
383 write!(self.writer, "{}", fmt_number_or_null(v))
385 fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) }
387 fn emit_char(&mut self, v: char) -> EncodeResult {
388 escape_char(self.writer, v)
390 fn emit_str(&mut self, v: &str) -> EncodeResult {
391 escape_str(self.writer, v)
394 fn emit_enum(&mut self, _name: &str, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
398 fn emit_enum_variant(&mut self,
402 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
403 // enums are encoded as strings or objects
405 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
407 escape_str(self.writer, name)
409 try!(write!(self.writer, "{{\"variant\":"));
410 try!(escape_str(self.writer, name));
411 try!(write!(self.writer, ",\"fields\":["));
413 write!(self.writer, "]}}")
417 fn emit_enum_variant_arg(&mut self,
419 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
421 try!(write!(self.writer, ","));
426 fn emit_enum_struct_variant(&mut self,
430 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
431 self.emit_enum_variant(name, id, cnt, f)
434 fn emit_enum_struct_variant_field(&mut self,
437 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
438 self.emit_enum_variant_arg(idx, f)
441 fn emit_struct(&mut self,
444 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
445 try!(write!(self.writer, "{{"));
447 write!(self.writer, "}}")
450 fn emit_struct_field(&mut self,
453 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
454 if idx != 0 { try!(write!(self.writer, ",")); }
455 try!(escape_str(self.writer, name));
456 try!(write!(self.writer, ":"));
460 fn emit_tuple(&mut self, len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
461 self.emit_seq(len, f)
463 fn emit_tuple_arg(&mut self,
465 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
466 self.emit_seq_elt(idx, f)
469 fn emit_tuple_struct(&mut self,
472 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
473 self.emit_seq(len, f)
475 fn emit_tuple_struct_arg(&mut self,
477 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
478 self.emit_seq_elt(idx, f)
481 fn emit_option(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
484 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
485 fn emit_option_some(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
489 fn emit_seq(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
490 try!(write!(self.writer, "["));
492 write!(self.writer, "]")
495 fn emit_seq_elt(&mut self, idx: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
497 try!(write!(self.writer, ","));
502 fn emit_map(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
503 try!(write!(self.writer, "{{"));
505 write!(self.writer, "}}")
508 fn emit_map_elt_key(&mut self,
510 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
511 if idx != 0 { try!(write!(self.writer, ",")) }
512 // ref #12967, make sure to wrap a key in double quotes,
513 // in the event that its of a type that omits them (eg numbers)
514 let mut buf = MemWriter::new();
515 // FIXME(14302) remove the transmute and unsafe block.
517 let mut check_encoder = Encoder::new(&mut buf);
518 try!(f(transmute(&mut check_encoder)));
520 let out = str::from_utf8_owned(buf.unwrap()).unwrap();
521 let out = out.as_slice();
522 let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
523 if needs_wrapping { try!(write!(self.writer, "\"")); }
525 if needs_wrapping { try!(write!(self.writer, "\"")); }
529 fn emit_map_elt_val(&mut self,
531 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
532 try!(write!(self.writer, ":"));
537 /// Another encoder for JSON, but prints out human-readable JSON instead of
539 pub struct PrettyEncoder<'a> {
540 writer: &'a mut io::Writer,
544 impl<'a> PrettyEncoder<'a> {
545 /// Creates a new encoder whose output will be written to the specified writer
546 pub fn new<'a>(writer: &'a mut io::Writer) -> PrettyEncoder<'a> {
547 PrettyEncoder { writer: writer, indent: 0 }
551 impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> {
552 fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
554 fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) }
555 fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) }
556 fn emit_u32(&mut self, v: u32) -> EncodeResult { self.emit_f64(v as f64) }
557 fn emit_u16(&mut self, v: u16) -> EncodeResult { self.emit_f64(v as f64) }
558 fn emit_u8(&mut self, v: u8) -> EncodeResult { self.emit_f64(v as f64) }
560 fn emit_int(&mut self, v: int) -> EncodeResult { self.emit_f64(v as f64) }
561 fn emit_i64(&mut self, v: i64) -> EncodeResult { self.emit_f64(v as f64) }
562 fn emit_i32(&mut self, v: i32) -> EncodeResult { self.emit_f64(v as f64) }
563 fn emit_i16(&mut self, v: i16) -> EncodeResult { self.emit_f64(v as f64) }
564 fn emit_i8(&mut self, v: i8) -> EncodeResult { self.emit_f64(v as f64) }
566 fn emit_bool(&mut self, v: bool) -> EncodeResult {
568 write!(self.writer, "true")
570 write!(self.writer, "false")
574 fn emit_f64(&mut self, v: f64) -> EncodeResult {
575 write!(self.writer, "{}", fmt_number_or_null(v))
577 fn emit_f32(&mut self, v: f32) -> EncodeResult {
578 self.emit_f64(v as f64)
581 fn emit_char(&mut self, v: char) -> EncodeResult {
582 escape_char(self.writer, v)
584 fn emit_str(&mut self, v: &str) -> EncodeResult {
585 escape_str(self.writer, v)
588 fn emit_enum(&mut self,
590 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
594 fn emit_enum_variant(&mut self,
598 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
600 escape_str(self.writer, name)
603 try!(write!(self.writer, "[\n"));
604 try!(spaces(self.writer, self.indent));
605 try!(escape_str(self.writer, name));
606 try!(write!(self.writer, ",\n"));
609 try!(write!(self.writer, "\n"));
610 try!(spaces(self.writer, self.indent));
611 write!(self.writer, "]")
615 fn emit_enum_variant_arg(&mut self,
617 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
619 try!(write!(self.writer, ",\n"));
621 try!(spaces(self.writer, self.indent));
625 fn emit_enum_struct_variant(&mut self,
629 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
630 self.emit_enum_variant(name, id, cnt, f)
633 fn emit_enum_struct_variant_field(&mut self,
636 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
637 self.emit_enum_variant_arg(idx, f)
641 fn emit_struct(&mut self,
644 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
646 write!(self.writer, "{{}}")
648 try!(write!(self.writer, "{{"));
652 try!(write!(self.writer, "\n"));
653 try!(spaces(self.writer, self.indent));
654 write!(self.writer, "}}")
658 fn emit_struct_field(&mut self,
661 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
663 try!(write!(self.writer, "\n"));
665 try!(write!(self.writer, ",\n"));
667 try!(spaces(self.writer, self.indent));
668 try!(escape_str(self.writer, name));
669 try!(write!(self.writer, ": "));
673 fn emit_tuple(&mut self,
675 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
676 self.emit_seq(len, f)
678 fn emit_tuple_arg(&mut self,
680 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
681 self.emit_seq_elt(idx, f)
684 fn emit_tuple_struct(&mut self,
687 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
688 self.emit_seq(len, f)
690 fn emit_tuple_struct_arg(&mut self,
692 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
693 self.emit_seq_elt(idx, f)
696 fn emit_option(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
699 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
700 fn emit_option_some(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
704 fn emit_seq(&mut self,
706 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
708 write!(self.writer, "[]")
710 try!(write!(self.writer, "["));
714 try!(write!(self.writer, "\n"));
715 try!(spaces(self.writer, self.indent));
716 write!(self.writer, "]")
720 fn emit_seq_elt(&mut self,
722 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
724 try!(write!(self.writer, "\n"));
726 try!(write!(self.writer, ",\n"));
728 try!(spaces(self.writer, self.indent));
732 fn emit_map(&mut self,
734 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
736 write!(self.writer, "{{}}")
738 try!(write!(self.writer, "{{"));
742 try!(write!(self.writer, "\n"));
743 try!(spaces(self.writer, self.indent));
744 write!(self.writer, "}}")
748 fn emit_map_elt_key(&mut self,
750 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
752 try!(write!(self.writer, "\n"));
754 try!(write!(self.writer, ",\n"));
756 try!(spaces(self.writer, self.indent));
757 // ref #12967, make sure to wrap a key in double quotes,
758 // in the event that its of a type that omits them (eg numbers)
759 let mut buf = MemWriter::new();
760 // FIXME(14302) remove the transmute and unsafe block.
762 let mut check_encoder = PrettyEncoder::new(&mut buf);
763 try!(f(transmute(&mut check_encoder)));
765 let out = str::from_utf8_owned(buf.unwrap()).unwrap();
766 let out = out.as_slice();
767 let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
768 if needs_wrapping { try!(write!(self.writer, "\"")); }
770 if needs_wrapping { try!(write!(self.writer, "\"")); }
774 fn emit_map_elt_val(&mut self,
776 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
777 try!(write!(self.writer, ": "));
782 impl<E: ::Encoder<S>, S> Encodable<E, S> for Json {
783 fn encode(&self, e: &mut E) -> Result<(), S> {
785 Number(v) => v.encode(e),
786 String(ref v) => v.encode(e),
787 Boolean(v) => v.encode(e),
788 List(ref v) => v.encode(e),
789 Object(ref v) => v.encode(e),
790 Null => e.emit_nil(),
796 /// Encodes a json value into an io::writer. Uses a single line.
797 pub fn to_writer(&self, writer: &mut io::Writer) -> EncodeResult {
798 let mut encoder = Encoder::new(writer);
799 self.encode(&mut encoder)
802 /// Encodes a json value into an io::writer.
803 /// Pretty-prints in a more readable format.
804 pub fn to_pretty_writer(&self, writer: &mut io::Writer) -> EncodeResult {
805 let mut encoder = PrettyEncoder::new(writer);
806 self.encode(&mut encoder)
809 /// Encodes a json value into a string
810 pub fn to_pretty_str(&self) -> String {
811 let mut s = MemWriter::new();
812 self.to_pretty_writer(&mut s as &mut io::Writer).unwrap();
813 str::from_utf8_owned(s.unwrap()).unwrap()
816 /// If the Json value is an Object, returns the value associated with the provided key.
817 /// Otherwise, returns None.
818 pub fn find<'a>(&'a self, key: &String) -> Option<&'a Json>{
820 &Object(ref map) => map.find(key),
825 /// Attempts to get a nested Json Object for each key in `keys`.
826 /// If any key is found not to exist, find_path will return None.
827 /// Otherwise, it will return the Json value associated with the final key.
828 pub fn find_path<'a>(&'a self, keys: &[&String]) -> Option<&'a Json>{
829 let mut target = self;
830 for key in keys.iter() {
831 match target.find(*key) {
832 Some(t) => { target = t; },
839 /// If the Json value is an Object, performs a depth-first search until
840 /// a value associated with the provided key is found. If no value is found
841 /// or the Json value is not an Object, returns None.
842 pub fn search<'a>(&'a self, key: &String) -> Option<&'a Json> {
844 &Object(ref map) => {
845 match map.find(key) {
846 Some(json_value) => Some(json_value),
848 let mut value : Option<&'a Json> = None;
849 for (_, v) in map.iter() {
850 value = v.search(key);
863 /// Returns true if the Json value is an Object. Returns false otherwise.
864 pub fn is_object<'a>(&'a self) -> bool {
865 self.as_object().is_some()
868 /// If the Json value is an Object, returns the associated TreeMap.
869 /// Returns None otherwise.
870 pub fn as_object<'a>(&'a self) -> Option<&'a Object> {
872 &Object(ref map) => Some(map),
877 /// Returns true if the Json value is a List. Returns false otherwise.
878 pub fn is_list<'a>(&'a self) -> bool {
879 self.as_list().is_some()
882 /// If the Json value is a List, returns the associated vector.
883 /// Returns None otherwise.
884 pub fn as_list<'a>(&'a self) -> Option<&'a List> {
886 &List(ref list) => Some(&*list),
891 /// Returns true if the Json value is a String. Returns false otherwise.
892 pub fn is_string<'a>(&'a self) -> bool {
893 self.as_string().is_some()
896 /// If the Json value is a String, returns the associated str.
897 /// Returns None otherwise.
898 pub fn as_string<'a>(&'a self) -> Option<&'a str> {
900 String(ref s) => Some(s.as_slice()),
905 /// Returns true if the Json value is a Number. Returns false otherwise.
906 pub fn is_number(&self) -> bool {
907 self.as_number().is_some()
910 /// If the Json value is a Number, returns the associated f64.
911 /// Returns None otherwise.
912 pub fn as_number(&self) -> Option<f64> {
914 &Number(n) => Some(n),
919 /// Returns true if the Json value is a Boolean. Returns false otherwise.
920 pub fn is_boolean(&self) -> bool {
921 self.as_boolean().is_some()
924 /// If the Json value is a Boolean, returns the associated bool.
925 /// Returns None otherwise.
926 pub fn as_boolean(&self) -> Option<bool> {
928 &Boolean(b) => Some(b),
933 /// Returns true if the Json value is a Null. Returns false otherwise.
934 pub fn is_null(&self) -> bool {
935 self.as_null().is_some()
938 /// If the Json value is a Null, returns ().
939 /// Returns None otherwise.
940 pub fn as_null(&self) -> Option<()> {
948 /// The output of the streaming parser.
949 #[deriving(PartialEq, Clone, Show)]
962 #[deriving(PartialEq, Show)]
964 // Parse a value in a list, true means first element.
966 // Parse ',' or ']' after an element in a list.
968 // Parse a key:value in an object, true means first element.
970 // Parse ',' or ']' after an element in an object.
974 // Expecting the stream to end.
976 // Parsing can't continue.
980 /// A Stack represents the current position of the parser in the logical
981 /// structure of the JSON stream.
982 /// For example foo.bar[3].x
984 stack: Vec<InternalStackElement>,
988 /// StackElements compose a Stack.
989 /// For example, Key("foo"), Key("bar"), Index(3) and Key("x") are the
990 /// StackElements compositing the stack that represents foo.bar[3].x
991 #[deriving(PartialEq, Clone, Show)]
992 pub enum StackElement<'l> {
997 // Internally, Key elements are stored as indices in a buffer to avoid
998 // allocating a string for every member of an object.
999 #[deriving(PartialEq, Clone, Show)]
1000 enum InternalStackElement {
1002 InternalKey(u16, u16), // start, size
1006 pub fn new() -> Stack {
1007 Stack { stack: Vec::new(), str_buffer: Vec::new() }
1010 /// Returns The number of elements in the Stack.
1011 pub fn len(&self) -> uint { self.stack.len() }
1013 /// Returns true if the stack is empty.
1014 pub fn is_empty(&self) -> bool { self.stack.is_empty() }
1016 /// Provides access to the StackElement at a given index.
1017 /// lower indices are at the bottom of the stack while higher indices are
1019 pub fn get<'l>(&'l self, idx: uint) -> StackElement<'l> {
1020 match *self.stack.get(idx) {
1021 InternalIndex(i) => { Index(i) }
1022 InternalKey(start, size) => {
1024 self.str_buffer.slice(start as uint, start as uint + size as uint)).unwrap())
1029 /// Compares this stack with an array of StackElements.
1030 pub fn is_equal_to(&self, rhs: &[StackElement]) -> bool {
1031 if self.stack.len() != rhs.len() { return false; }
1032 for i in range(0, rhs.len()) {
1033 if self.get(i) != rhs[i] { return false; }
1038 /// Returns true if the bottom-most elements of this stack are the same as
1039 /// the ones passed as parameter.
1040 pub fn starts_with(&self, rhs: &[StackElement]) -> bool {
1041 if self.stack.len() < rhs.len() { return false; }
1042 for i in range(0, rhs.len()) {
1043 if self.get(i) != rhs[i] { return false; }
1048 /// Returns true if the top-most elements of this stack are the same as
1049 /// the ones passed as parameter.
1050 pub fn ends_with(&self, rhs: &[StackElement]) -> bool {
1051 if self.stack.len() < rhs.len() { return false; }
1052 let offset = self.stack.len() - rhs.len();
1053 for i in range(0, rhs.len()) {
1054 if self.get(i + offset) != rhs[i] { return false; }
1059 /// Returns the top-most element (if any).
1060 pub fn top<'l>(&'l self) -> Option<StackElement<'l>> {
1061 return match self.stack.last() {
1063 Some(&InternalIndex(i)) => Some(Index(i)),
1064 Some(&InternalKey(start, size)) => {
1065 Some(Key(str::from_utf8(
1066 self.str_buffer.slice(start as uint, (start+size) as uint)
1072 // Used by Parser to insert Key elements at the top of the stack.
1073 fn push_key(&mut self, key: String) {
1074 self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
1075 for c in key.as_bytes().iter() {
1076 self.str_buffer.push(*c);
1080 // Used by Parser to insert Index elements at the top of the stack.
1081 fn push_index(&mut self, index: u32) {
1082 self.stack.push(InternalIndex(index));
1085 // Used by Parser to remove the top-most element of the stack.
1087 assert!(!self.is_empty());
1088 match *self.stack.last().unwrap() {
1089 InternalKey(_, sz) => {
1090 let new_size = self.str_buffer.len() - sz as uint;
1091 self.str_buffer.truncate(new_size);
1093 InternalIndex(_) => {}
1098 // Used by Parser to test whether the top-most element is an index.
1099 fn last_is_index(&self) -> bool {
1100 if self.is_empty() { return false; }
1101 return match *self.stack.last().unwrap() {
1102 InternalIndex(_) => true,
1107 // Used by Parser to increment the index of the top-most element.
1108 fn bump_index(&mut self) {
1109 let len = self.stack.len();
1110 let idx = match *self.stack.last().unwrap() {
1111 InternalIndex(i) => { i + 1 }
1114 *self.stack.get_mut(len - 1) = InternalIndex(idx);
1118 /// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
1119 /// an iterator of char.
1120 pub struct Parser<T> {
1125 // We maintain a stack representing where we are in the logical structure
1126 // of the JSON stream.
1128 // A state machine is kept to make it possible to interrupt and resume parsing.
1132 impl<T: Iterator<char>> Iterator<JsonEvent> for Parser<T> {
1133 fn next(&mut self) -> Option<JsonEvent> {
1134 if self.state == ParseFinished {
1138 if self.state == ParseBeforeFinish {
1139 self.parse_whitespace();
1140 // Make sure there is no trailing characters.
1142 self.state = ParseFinished;
1145 return Some(self.error_event(TrailingCharacters));
1149 return Some(self.parse());
1153 impl<T: Iterator<char>> Parser<T> {
1154 /// Creates the JSON parser.
1155 pub fn new(rdr: T) -> Parser<T> {
1156 let mut p = Parser {
1161 stack: Stack::new(),
1168 /// Provides access to the current position in the logical structure of the
1170 pub fn stack<'l>(&'l self) -> &'l Stack {
1174 fn eof(&self) -> bool { self.ch.is_none() }
1175 fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
1176 fn bump(&mut self) {
1177 self.ch = self.rdr.next();
1179 if self.ch_is('\n') {
1187 fn next_char(&mut self) -> Option<char> {
1191 fn ch_is(&self, c: char) -> bool {
1195 fn error<T>(&self, reason: ErrorCode) -> Result<T, ParserError> {
1196 Err(SyntaxError(reason, self.line, self.col))
1199 fn parse_whitespace(&mut self) {
1200 while self.ch_is(' ') ||
1203 self.ch_is('\r') { self.bump(); }
1206 fn parse_number(&mut self) -> Result<f64, ParserError> {
1209 if self.ch_is('-') {
1214 let mut res = try!(self.parse_integer());
1216 if self.ch_is('.') {
1217 res = try!(self.parse_decimal(res));
1220 if self.ch_is('e') || self.ch_is('E') {
1221 res = try!(self.parse_exponent(res));
1227 fn parse_integer(&mut self) -> Result<f64, ParserError> {
1230 match self.ch_or_null() {
1234 // A leading '0' must be the only digit before the decimal point.
1235 match self.ch_or_null() {
1236 '0' .. '9' => return self.error(InvalidNumber),
1242 match self.ch_or_null() {
1245 res += ((c as int) - ('0' as int)) as f64;
1252 _ => return self.error(InvalidNumber),
1257 fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1260 // Make sure a digit follows the decimal place.
1261 match self.ch_or_null() {
1263 _ => return self.error(InvalidNumber)
1268 match self.ch_or_null() {
1271 res += (((c as int) - ('0' as int)) as f64) * dec;
1281 fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1285 let mut neg_exp = false;
1287 if self.ch_is('+') {
1289 } else if self.ch_is('-') {
1294 // Make sure a digit follows the exponent place.
1295 match self.ch_or_null() {
1297 _ => return self.error(InvalidNumber)
1300 match self.ch_or_null() {
1303 exp += (c as uint) - ('0' as uint);
1311 let exp = num::pow(10_f64, exp);
1321 fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1324 while i < 4 && !self.eof() {
1326 n = match self.ch_or_null() {
1327 c @ '0' .. '9' => n * 16 + ((c as u16) - ('0' as u16)),
1328 'a' | 'A' => n * 16 + 10,
1329 'b' | 'B' => n * 16 + 11,
1330 'c' | 'C' => n * 16 + 12,
1331 'd' | 'D' => n * 16 + 13,
1332 'e' | 'E' => n * 16 + 14,
1333 'f' | 'F' => n * 16 + 15,
1334 _ => return self.error(InvalidEscape)
1340 // Error out if we didn't parse 4 digits.
1342 return self.error(InvalidEscape);
1348 fn parse_str(&mut self) -> Result<String, ParserError> {
1349 let mut escape = false;
1350 let mut res = String::new();
1355 return self.error(EOFWhileParsingString);
1359 match self.ch_or_null() {
1360 '"' => res.push_char('"'),
1361 '\\' => res.push_char('\\'),
1362 '/' => res.push_char('/'),
1363 'b' => res.push_char('\x08'),
1364 'f' => res.push_char('\x0c'),
1365 'n' => res.push_char('\n'),
1366 'r' => res.push_char('\r'),
1367 't' => res.push_char('\t'),
1368 'u' => match try!(self.decode_hex_escape()) {
1369 0xDC00 .. 0xDFFF => return self.error(LoneLeadingSurrogateInHexEscape),
1371 // Non-BMP characters are encoded as a sequence of
1372 // two hex escapes, representing UTF-16 surrogates.
1373 n1 @ 0xD800 .. 0xDBFF => {
1374 match (self.next_char(), self.next_char()) {
1375 (Some('\\'), Some('u')) => (),
1376 _ => return self.error(UnexpectedEndOfHexEscape),
1379 let buf = [n1, try!(self.decode_hex_escape())];
1380 match str::utf16_items(buf.as_slice()).next() {
1381 Some(ScalarValue(c)) => res.push_char(c),
1382 _ => return self.error(LoneLeadingSurrogateInHexEscape),
1386 n => match char::from_u32(n as u32) {
1387 Some(c) => res.push_char(c),
1388 None => return self.error(InvalidUnicodeCodePoint),
1391 _ => return self.error(InvalidEscape),
1394 } else if self.ch_is('\\') {
1402 Some(c) => res.push_char(c),
1403 None => unreachable!()
1409 // Invoked at each iteration, consumes the stream until it has enough
1410 // information to return a JsonEvent.
1411 // Manages an internal state so that parsing can be interrupted and resumed.
1412 // Also keeps track of the position in the logical structure of the json
1413 // stream int the form of a stack that can be queried by the user using the
1415 fn parse(&mut self) -> JsonEvent {
1417 // The only paths where the loop can spin a new iteration
1418 // are in the cases ParseListComma and ParseObjectComma if ','
1419 // is parsed. In these cases the state is set to (respectively)
1420 // ParseList(false) and ParseObject(false), which always return,
1421 // so there is no risk of getting stuck in an infinite loop.
1422 // All other paths return before the end of the loop's iteration.
1423 self.parse_whitespace();
1427 return self.parse_start();
1429 ParseList(first) => {
1430 return self.parse_list(first);
1433 match self.parse_list_comma_or_end() {
1434 Some(evt) => { return evt; }
1438 ParseObject(first) => {
1439 return self.parse_object(first);
1441 ParseObjectComma => {
1443 if self.ch_is(',') {
1444 self.state = ParseObject(false);
1447 return self.parse_object_end();
1451 return self.error_event(InvalidSyntax);
1457 fn parse_start(&mut self) -> JsonEvent {
1458 let val = self.parse_value();
1459 self.state = match val {
1460 Error(_) => { ParseFinished }
1461 ListStart => { ParseList(true) }
1462 ObjectStart => { ParseObject(true) }
1463 _ => { ParseBeforeFinish }
1468 fn parse_list(&mut self, first: bool) -> JsonEvent {
1469 if self.ch_is(']') {
1471 return self.error_event(InvalidSyntax);
1473 if self.stack.is_empty() {
1474 self.state = ParseBeforeFinish;
1476 self.state = if self.stack.last_is_index() {
1486 self.stack.push_index(0);
1489 let val = self.parse_value();
1491 self.state = match val {
1492 Error(_) => { ParseFinished }
1493 ListStart => { ParseList(true) }
1494 ObjectStart => { ParseObject(true) }
1495 _ => { ParseListComma }
1500 fn parse_list_comma_or_end(&mut self) -> Option<JsonEvent> {
1501 if self.ch_is(',') {
1502 self.stack.bump_index();
1503 self.state = ParseList(false);
1506 } else if self.ch_is(']') {
1508 if self.stack.is_empty() {
1509 self.state = ParseBeforeFinish;
1511 self.state = if self.stack.last_is_index() {
1518 return Some(ListEnd);
1519 } else if self.eof() {
1520 return Some(self.error_event(EOFWhileParsingList));
1522 return Some(self.error_event(InvalidSyntax));
1526 fn parse_object(&mut self, first: bool) -> JsonEvent {
1527 if self.ch_is('}') {
1531 if self.stack.is_empty() {
1532 self.state = ParseBeforeFinish;
1534 self.state = if self.stack.last_is_index() {
1544 return self.error_event(EOFWhileParsingObject);
1546 if !self.ch_is('"') {
1547 return self.error_event(KeyMustBeAString);
1549 let s = match self.parse_str() {
1552 self.state = ParseFinished;
1556 self.parse_whitespace();
1558 return self.error_event(EOFWhileParsingObject);
1559 } else if self.ch_or_null() != ':' {
1560 return self.error_event(ExpectedColon);
1562 self.stack.push_key(s);
1564 self.parse_whitespace();
1566 let val = self.parse_value();
1568 self.state = match val {
1569 Error(_) => { ParseFinished }
1570 ListStart => { ParseList(true) }
1571 ObjectStart => { ParseObject(true) }
1572 _ => { ParseObjectComma }
1577 fn parse_object_end(&mut self) -> JsonEvent {
1578 if self.ch_is('}') {
1579 if self.stack.is_empty() {
1580 self.state = ParseBeforeFinish;
1582 self.state = if self.stack.last_is_index() {
1590 } else if self.eof() {
1591 self.error_event(EOFWhileParsingObject)
1593 self.error_event(InvalidSyntax)
1597 fn parse_value(&mut self) -> JsonEvent {
1598 if self.eof() { return self.error_event(EOFWhileParsingValue); }
1599 match self.ch_or_null() {
1600 'n' => { self.parse_ident("ull", NullValue) }
1601 't' => { self.parse_ident("rue", BooleanValue(true)) }
1602 'f' => { self.parse_ident("alse", BooleanValue(false)) }
1603 '0' .. '9' | '-' => match self.parse_number() {
1604 Ok(f) => NumberValue(f),
1607 '"' => match self.parse_str() {
1608 Ok(s) => StringValue(s),
1619 _ => { self.error_event(InvalidSyntax) }
1623 fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
1624 if ident.chars().all(|c| Some(c) == self.next_char()) {
1628 Error(SyntaxError(InvalidSyntax, self.line, self.col))
1632 fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
1633 self.state = ParseFinished;
1634 Error(SyntaxError(reason, self.line, self.col))
1638 /// A Builder consumes a json::Parser to create a generic Json structure.
1639 pub struct Builder<T> {
1641 token: Option<JsonEvent>,
1644 impl<T: Iterator<char>> Builder<T> {
1645 /// Create a JSON Builder.
1646 pub fn new(src: T) -> Builder<T> {
1647 Builder { parser: Parser::new(src), token: None, }
1650 // Decode a Json value from a Parser.
1651 pub fn build(&mut self) -> Result<Json, BuilderError> {
1653 let result = self.build_value();
1657 Some(Error(e)) => { return Err(e); }
1658 ref tok => { fail!("unexpected token {}", tok.clone()); }
1663 fn bump(&mut self) {
1664 self.token = self.parser.next();
1667 fn build_value(&mut self) -> Result<Json, BuilderError> {
1668 return match self.token {
1669 Some(NullValue) => { Ok(Null) }
1670 Some(NumberValue(n)) => { Ok(Number(n)) }
1671 Some(BooleanValue(b)) => { Ok(Boolean(b)) }
1672 Some(StringValue(ref mut s)) => {
1673 let mut temp = String::new();
1677 Some(Error(e)) => { Err(e) }
1678 Some(ListStart) => { self.build_list() }
1679 Some(ObjectStart) => { self.build_object() }
1680 Some(ObjectEnd) => { self.parser.error(InvalidSyntax) }
1681 Some(ListEnd) => { self.parser.error(InvalidSyntax) }
1682 None => { self.parser.error(EOFWhileParsingValue) }
1686 fn build_list(&mut self) -> Result<Json, BuilderError> {
1688 let mut values = Vec::new();
1691 if self.token == Some(ListEnd) {
1692 return Ok(List(values.move_iter().collect()));
1694 match self.build_value() {
1695 Ok(v) => values.push(v),
1696 Err(e) => { return Err(e) }
1702 fn build_object(&mut self) -> Result<Json, BuilderError> {
1705 let mut values = TreeMap::new();
1709 Some(ObjectEnd) => { return Ok(Object(values)); }
1710 Some(Error(e)) => { return Err(e); }
1714 let key = match self.parser.stack().top() {
1715 Some(Key(k)) => { k.to_string() }
1716 _ => { fail!("invalid state"); }
1718 match self.build_value() {
1719 Ok(value) => { values.insert(key, value); }
1720 Err(e) => { return Err(e); }
1724 return self.parser.error(EOFWhileParsingObject);
1728 /// Decodes a json value from an `&mut io::Reader`
1729 pub fn from_reader(rdr: &mut io::Reader) -> Result<Json, BuilderError> {
1730 let contents = match rdr.read_to_end() {
1732 Err(e) => return Err(io_error_to_error(e))
1734 let s = match str::from_utf8_owned(contents) {
1736 _ => return Err(SyntaxError(NotUtf8, 0, 0))
1738 let mut builder = Builder::new(s.as_slice().chars());
1742 /// Decodes a json value from a string
1743 pub fn from_str(s: &str) -> Result<Json, BuilderError> {
1744 let mut builder = Builder::new(s.chars());
1748 /// A structure to decode JSON to values in rust.
1749 pub struct Decoder {
1754 /// Creates a new decoder instance for decoding the specified JSON value.
1755 pub fn new(json: Json) -> Decoder {
1756 Decoder { stack: vec![json] }
1761 fn pop(&mut self) -> Json {
1762 self.stack.pop().unwrap()
1766 macro_rules! expect(
1767 ($e:expr, Null) => ({
1770 other => Err(ExpectedError("Null".to_string(),
1771 format!("{}", other)))
1774 ($e:expr, $t:ident) => ({
1778 Err(ExpectedError(stringify!($t).to_string(),
1779 format!("{}", other)))
1785 impl ::Decoder<DecoderError> for Decoder {
1786 fn read_nil(&mut self) -> DecodeResult<()> {
1788 expect!(self.pop(), Null)
1791 fn read_u64(&mut self) -> DecodeResult<u64 > { Ok(try!(self.read_f64()) as u64) }
1792 fn read_u32(&mut self) -> DecodeResult<u32 > { Ok(try!(self.read_f64()) as u32) }
1793 fn read_u16(&mut self) -> DecodeResult<u16 > { Ok(try!(self.read_f64()) as u16) }
1794 fn read_u8 (&mut self) -> DecodeResult<u8 > { Ok(try!(self.read_f64()) as u8) }
1795 fn read_uint(&mut self) -> DecodeResult<uint> { Ok(try!(self.read_f64()) as uint) }
1797 fn read_i64(&mut self) -> DecodeResult<i64> { Ok(try!(self.read_f64()) as i64) }
1798 fn read_i32(&mut self) -> DecodeResult<i32> { Ok(try!(self.read_f64()) as i32) }
1799 fn read_i16(&mut self) -> DecodeResult<i16> { Ok(try!(self.read_f64()) as i16) }
1800 fn read_i8 (&mut self) -> DecodeResult<i8 > { Ok(try!(self.read_f64()) as i8) }
1801 fn read_int(&mut self) -> DecodeResult<int> { Ok(try!(self.read_f64()) as int) }
1803 fn read_bool(&mut self) -> DecodeResult<bool> {
1804 debug!("read_bool");
1805 expect!(self.pop(), Boolean)
1808 fn read_f64(&mut self) -> DecodeResult<f64> {
1813 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
1814 // is going to have a string here, as per JSON spec.
1815 Ok(std::from_str::from_str(s.as_slice()).unwrap())
1817 Null => Ok(f64::NAN),
1818 value => Err(ExpectedError("Number".to_string(), format!("{}", value)))
1822 fn read_f32(&mut self) -> DecodeResult<f32> { self.read_f64().map(|x| x as f32) }
1824 fn read_char(&mut self) -> DecodeResult<char> {
1825 let s = try!(self.read_str());
1827 let mut it = s.as_slice().chars();
1828 match (it.next(), it.next()) {
1829 // exactly one character
1830 (Some(c), None) => return Ok(c),
1834 Err(ExpectedError("single character string".to_string(), format!("{}", s)))
1837 fn read_str(&mut self) -> DecodeResult<String> {
1839 expect!(self.pop(), String)
1842 fn read_enum<T>(&mut self,
1844 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
1845 debug!("read_enum({})", name);
1849 fn read_enum_variant<T>(&mut self,
1851 f: |&mut Decoder, uint| -> DecodeResult<T>)
1852 -> DecodeResult<T> {
1853 debug!("read_enum_variant(names={})", names);
1854 let name = match self.pop() {
1857 let n = match o.pop(&"variant".to_string()) {
1858 Some(String(s)) => s,
1860 return Err(ExpectedError("String".to_string(), format!("{}", val)))
1863 return Err(MissingFieldError("variant".to_string()))
1866 match o.pop(&"fields".to_string()) {
1868 for field in l.move_iter().rev() {
1869 self.stack.push(field);
1873 return Err(ExpectedError("List".to_string(), format!("{}", val)))
1876 return Err(MissingFieldError("fields".to_string()))
1882 return Err(ExpectedError("String or Object".to_string(), format!("{}", json)))
1885 let idx = match names.iter()
1886 .position(|n| str::eq_slice(*n, name.as_slice())) {
1888 None => return Err(UnknownVariantError(name))
1893 fn read_enum_variant_arg<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
1894 -> DecodeResult<T> {
1895 debug!("read_enum_variant_arg(idx={})", idx);
1899 fn read_enum_struct_variant<T>(&mut self,
1901 f: |&mut Decoder, uint| -> DecodeResult<T>)
1902 -> DecodeResult<T> {
1903 debug!("read_enum_struct_variant(names={})", names);
1904 self.read_enum_variant(names, f)
1908 fn read_enum_struct_variant_field<T>(&mut self,
1911 f: |&mut Decoder| -> DecodeResult<T>)
1912 -> DecodeResult<T> {
1913 debug!("read_enum_struct_variant_field(name={}, idx={})", name, idx);
1914 self.read_enum_variant_arg(idx, f)
1917 fn read_struct<T>(&mut self,
1920 f: |&mut Decoder| -> DecodeResult<T>)
1921 -> DecodeResult<T> {
1922 debug!("read_struct(name={}, len={})", name, len);
1923 let value = try!(f(self));
1928 fn read_struct_field<T>(&mut self,
1931 f: |&mut Decoder| -> DecodeResult<T>)
1932 -> DecodeResult<T> {
1933 debug!("read_struct_field(name={}, idx={})", name, idx);
1934 let mut obj = try!(expect!(self.pop(), Object));
1936 let value = match obj.pop(&name.to_string()) {
1937 None => return Err(MissingFieldError(name.to_string())),
1939 self.stack.push(json);
1943 self.stack.push(Object(obj));
1947 fn read_tuple<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
1948 debug!("read_tuple()");
1952 fn read_tuple_arg<T>(&mut self,
1954 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
1955 debug!("read_tuple_arg(idx={})", idx);
1956 self.read_seq_elt(idx, f)
1959 fn read_tuple_struct<T>(&mut self,
1961 f: |&mut Decoder, uint| -> DecodeResult<T>)
1962 -> DecodeResult<T> {
1963 debug!("read_tuple_struct(name={})", name);
1967 fn read_tuple_struct_arg<T>(&mut self,
1969 f: |&mut Decoder| -> DecodeResult<T>)
1970 -> DecodeResult<T> {
1971 debug!("read_tuple_struct_arg(idx={})", idx);
1972 self.read_tuple_arg(idx, f)
1975 fn read_option<T>(&mut self, f: |&mut Decoder, bool| -> DecodeResult<T>) -> DecodeResult<T> {
1977 Null => f(self, false),
1978 value => { self.stack.push(value); f(self, true) }
1982 fn read_seq<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
1983 debug!("read_seq()");
1984 let list = try!(expect!(self.pop(), List));
1985 let len = list.len();
1986 for v in list.move_iter().rev() {
1992 fn read_seq_elt<T>(&mut self,
1994 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
1995 debug!("read_seq_elt(idx={})", idx);
1999 fn read_map<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
2000 debug!("read_map()");
2001 let obj = try!(expect!(self.pop(), Object));
2002 let len = obj.len();
2003 for (key, value) in obj.move_iter() {
2004 self.stack.push(value);
2005 self.stack.push(String(key));
2010 fn read_map_elt_key<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
2011 -> DecodeResult<T> {
2012 debug!("read_map_elt_key(idx={})", idx);
2016 fn read_map_elt_val<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
2017 -> DecodeResult<T> {
2018 debug!("read_map_elt_val(idx={})", idx);
2023 /// A trait for converting values to JSON
2025 /// Converts the value of `self` to an instance of JSON
2026 fn to_json(&self) -> Json;
2029 macro_rules! to_json_impl(
2031 $(impl ToJson for $t {
2032 fn to_json(&self) -> Json { Number(*self as f64) }
2037 to_json_impl!(int, i8, i16, i32, i64, uint, u8, u16, u32, u64)
2039 impl ToJson for Json {
2040 fn to_json(&self) -> Json { self.clone() }
2043 impl ToJson for f32 {
2044 fn to_json(&self) -> Json { (*self as f64).to_json() }
2047 impl ToJson for f64 {
2048 fn to_json(&self) -> Json {
2049 match self.classify() {
2050 FPNaN | FPInfinite => Null,
2056 impl ToJson for () {
2057 fn to_json(&self) -> Json { Null }
2060 impl ToJson for bool {
2061 fn to_json(&self) -> Json { Boolean(*self) }
2064 impl ToJson for String {
2065 fn to_json(&self) -> Json { String((*self).clone()) }
2068 macro_rules! tuple_impl {
2069 // use variables to indicate the arity of the tuple
2070 ($($tyvar:ident),* ) => {
2071 // the trailing commas are for the 1 tuple
2073 $( $tyvar : ToJson ),*
2074 > ToJson for ( $( $tyvar ),* , ) {
2077 #[allow(uppercase_variables)]
2078 fn to_json(&self) -> Json {
2080 ($(ref $tyvar),*,) => List(vec![$($tyvar.to_json()),*])
2089 tuple_impl!{A, B, C}
2090 tuple_impl!{A, B, C, D}
2091 tuple_impl!{A, B, C, D, E}
2092 tuple_impl!{A, B, C, D, E, F}
2093 tuple_impl!{A, B, C, D, E, F, G}
2094 tuple_impl!{A, B, C, D, E, F, G, H}
2095 tuple_impl!{A, B, C, D, E, F, G, H, I}
2096 tuple_impl!{A, B, C, D, E, F, G, H, I, J}
2097 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K}
2098 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L}
2100 impl<'a, A: ToJson> ToJson for &'a [A] {
2101 fn to_json(&self) -> Json { List(self.iter().map(|elt| elt.to_json()).collect()) }
2104 impl<A: ToJson> ToJson for Vec<A> {
2105 fn to_json(&self) -> Json { List(self.iter().map(|elt| elt.to_json()).collect()) }
2108 impl<A: ToJson> ToJson for TreeMap<String, A> {
2109 fn to_json(&self) -> Json {
2110 let mut d = TreeMap::new();
2111 for (key, value) in self.iter() {
2112 d.insert((*key).clone(), value.to_json());
2118 impl<A: ToJson> ToJson for HashMap<String, A> {
2119 fn to_json(&self) -> Json {
2120 let mut d = TreeMap::new();
2121 for (key, value) in self.iter() {
2122 d.insert((*key).clone(), value.to_json());
2128 impl<A:ToJson> ToJson for Option<A> {
2129 fn to_json(&self) -> Json {
2132 Some(ref value) => value.to_json()
2137 impl fmt::Show for Json {
2138 /// Encodes a json value into a string
2139 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2140 self.to_writer(f).map_err(|_| fmt::WriteError)
2144 impl std::from_str::FromStr for Json {
2145 fn from_str(s: &str) -> Option<Json> {
2153 use self::test::Bencher;
2154 use {Encodable, Decodable};
2155 use super::{Encoder, Decoder, Error, Boolean, Number, List, String, Null,
2156 PrettyEncoder, Object, Json, from_str, ParseError, ExpectedError,
2157 MissingFieldError, UnknownVariantError, DecodeResult, DecoderError,
2158 JsonEvent, Parser, StackElement,
2159 ObjectStart, ObjectEnd, ListStart, ListEnd, BooleanValue, NumberValue, StringValue,
2160 NullValue, SyntaxError, Key, Index, Stack,
2161 InvalidSyntax, InvalidNumber, EOFWhileParsingObject, EOFWhileParsingList,
2162 EOFWhileParsingValue, EOFWhileParsingString, KeyMustBeAString, ExpectedColon,
2163 TrailingCharacters};
2164 use std::{f32, f64, io};
2165 use std::collections::TreeMap;
2167 #[deriving(PartialEq, Encodable, Decodable, Show)]
2173 #[deriving(PartialEq, Encodable, Decodable, Show)]
2180 #[deriving(PartialEq, Encodable, Decodable, Show)]
2185 fn mk_object(items: &[(String, Json)]) -> Json {
2186 let mut d = TreeMap::new();
2188 for item in items.iter() {
2190 (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
2198 fn test_from_str_trait() {
2200 assert!(::std::from_str::from_str::<Json>(s).unwrap() == from_str(s).unwrap());
2204 fn test_write_null() {
2205 assert_eq!(Null.to_str().into_string(), "null".to_string());
2206 assert_eq!(Null.to_pretty_str().into_string(), "null".to_string());
2211 fn test_write_number() {
2212 assert_eq!(Number(3.0).to_str().into_string(), "3".to_string());
2213 assert_eq!(Number(3.0).to_pretty_str().into_string(), "3".to_string());
2215 assert_eq!(Number(3.1).to_str().into_string(), "3.1".to_string());
2216 assert_eq!(Number(3.1).to_pretty_str().into_string(), "3.1".to_string());
2218 assert_eq!(Number(-1.5).to_str().into_string(), "-1.5".to_string());
2219 assert_eq!(Number(-1.5).to_pretty_str().into_string(), "-1.5".to_string());
2221 assert_eq!(Number(0.5).to_str().into_string(), "0.5".to_string());
2222 assert_eq!(Number(0.5).to_pretty_str().into_string(), "0.5".to_string());
2224 assert_eq!(Number(f64::NAN).to_str().into_string(), "null".to_string());
2225 assert_eq!(Number(f64::NAN).to_pretty_str().into_string(), "null".to_string());
2227 assert_eq!(Number(f64::INFINITY).to_str().into_string(), "null".to_string());
2228 assert_eq!(Number(f64::INFINITY).to_pretty_str().into_string(), "null".to_string());
2230 assert_eq!(Number(f64::NEG_INFINITY).to_str().into_string(), "null".to_string());
2231 assert_eq!(Number(f64::NEG_INFINITY).to_pretty_str().into_string(), "null".to_string());
2235 fn test_write_str() {
2236 assert_eq!(String("".to_string()).to_str().into_string(), "\"\"".to_string());
2237 assert_eq!(String("".to_string()).to_pretty_str().into_string(), "\"\"".to_string());
2239 assert_eq!(String("foo".to_string()).to_str().into_string(), "\"foo\"".to_string());
2240 assert_eq!(String("foo".to_string()).to_pretty_str().into_string(), "\"foo\"".to_string());
2244 fn test_write_bool() {
2245 assert_eq!(Boolean(true).to_str().into_string(), "true".to_string());
2246 assert_eq!(Boolean(true).to_pretty_str().into_string(), "true".to_string());
2248 assert_eq!(Boolean(false).to_str().into_string(), "false".to_string());
2249 assert_eq!(Boolean(false).to_pretty_str().into_string(), "false".to_string());
2253 fn test_write_list() {
2254 assert_eq!(List(vec![]).to_str().into_string(), "[]".to_string());
2255 assert_eq!(List(vec![]).to_pretty_str().into_string(), "[]".to_string());
2257 assert_eq!(List(vec![Boolean(true)]).to_str().into_string(), "[true]".to_string());
2259 List(vec![Boolean(true)]).to_pretty_str().into_string(),
2266 let long_test_list = List(vec![
2269 List(vec![String("foo\nbar".to_string()), Number(3.5)])]);
2271 assert_eq!(long_test_list.to_str().into_string(),
2272 "[false,null,[\"foo\\nbar\",3.5]]".to_string());
2274 long_test_list.to_pretty_str().into_string(),
2288 fn test_write_object() {
2289 assert_eq!(mk_object([]).to_str().into_string(), "{}".to_string());
2290 assert_eq!(mk_object([]).to_pretty_str().into_string(), "{}".to_string());
2294 ("a".to_string(), Boolean(true))
2295 ]).to_str().into_string(),
2296 "{\"a\":true}".to_string()
2299 mk_object([("a".to_string(), Boolean(true))]).to_pretty_str(),
2306 let complex_obj = mk_object([
2307 ("b".to_string(), List(vec![
2308 mk_object([("c".to_string(), String("\x0c\r".to_string()))]),
2309 mk_object([("d".to_string(), String("".to_string()))])
2314 complex_obj.to_str().into_string(),
2317 {\"c\":\"\\f\\r\"},\
2323 complex_obj.to_pretty_str().into_string(),
2328 \"c\": \"\\f\\r\"\n \
2338 ("a".to_string(), Boolean(true)),
2339 ("b".to_string(), List(vec![
2340 mk_object([("c".to_string(), String("\x0c\r".to_string()))]),
2341 mk_object([("d".to_string(), String("".to_string()))])
2345 // We can't compare the strings directly because the object fields be
2346 // printed in a different order.
2347 assert_eq!(a.clone(), from_str(a.to_str().as_slice()).unwrap());
2348 assert_eq!(a.clone(),
2349 from_str(a.to_pretty_str().as_slice()).unwrap());
2352 fn with_str_writer(f: |&mut io::Writer|) -> String {
2353 use std::io::MemWriter;
2356 let mut m = MemWriter::new();
2357 f(&mut m as &mut io::Writer);
2358 str::from_utf8(m.unwrap().as_slice()).unwrap().to_string()
2362 fn test_write_enum() {
2365 with_str_writer(|writer| {
2366 let mut encoder = Encoder::new(writer);
2367 animal.encode(&mut encoder).unwrap();
2369 "\"Dog\"".to_string()
2372 with_str_writer(|writer| {
2373 let mut encoder = PrettyEncoder::new(writer);
2374 animal.encode(&mut encoder).unwrap();
2376 "\"Dog\"".to_string()
2379 let animal = Frog("Henry".to_string(), 349);
2381 with_str_writer(|writer| {
2382 let mut encoder = Encoder::new(writer);
2383 animal.encode(&mut encoder).unwrap();
2385 "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}".to_string()
2388 with_str_writer(|writer| {
2389 let mut encoder = PrettyEncoder::new(writer);
2390 animal.encode(&mut encoder).unwrap();
2402 fn test_write_some() {
2403 let value = Some("jodhpurs".to_string());
2404 let s = with_str_writer(|writer| {
2405 let mut encoder = Encoder::new(writer);
2406 value.encode(&mut encoder).unwrap();
2408 assert_eq!(s, "\"jodhpurs\"".to_string());
2410 let value = Some("jodhpurs".to_string());
2411 let s = with_str_writer(|writer| {
2412 let mut encoder = PrettyEncoder::new(writer);
2413 value.encode(&mut encoder).unwrap();
2415 assert_eq!(s, "\"jodhpurs\"".to_string());
2419 fn test_write_none() {
2420 let value: Option<String> = None;
2421 let s = with_str_writer(|writer| {
2422 let mut encoder = Encoder::new(writer);
2423 value.encode(&mut encoder).unwrap();
2425 assert_eq!(s, "null".to_string());
2427 let s = with_str_writer(|writer| {
2428 let mut encoder = Encoder::new(writer);
2429 value.encode(&mut encoder).unwrap();
2431 assert_eq!(s, "null".to_string());
2435 fn test_trailing_characters() {
2436 assert_eq!(from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2437 assert_eq!(from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2438 assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
2439 assert_eq!(from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2)));
2440 assert_eq!(from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2441 assert_eq!(from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2445 fn test_read_identifiers() {
2446 assert_eq!(from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2447 assert_eq!(from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2448 assert_eq!(from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2449 assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2450 assert_eq!(from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2451 assert_eq!(from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3)));
2453 assert_eq!(from_str("null"), Ok(Null));
2454 assert_eq!(from_str("true"), Ok(Boolean(true)));
2455 assert_eq!(from_str("false"), Ok(Boolean(false)));
2456 assert_eq!(from_str(" null "), Ok(Null));
2457 assert_eq!(from_str(" true "), Ok(Boolean(true)));
2458 assert_eq!(from_str(" false "), Ok(Boolean(false)));
2462 fn test_decode_identifiers() {
2463 let v: () = super::decode("null").unwrap();
2466 let v: bool = super::decode("true").unwrap();
2467 assert_eq!(v, true);
2469 let v: bool = super::decode("false").unwrap();
2470 assert_eq!(v, false);
2474 fn test_read_number() {
2475 assert_eq!(from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2476 assert_eq!(from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1)));
2477 assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2478 assert_eq!(from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2)));
2479 assert_eq!(from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2)));
2480 assert_eq!(from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3)));
2481 assert_eq!(from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3)));
2482 assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
2484 assert_eq!(from_str("3"), Ok(Number(3.0)));
2485 assert_eq!(from_str("3.1"), Ok(Number(3.1)));
2486 assert_eq!(from_str("-1.2"), Ok(Number(-1.2)));
2487 assert_eq!(from_str("0.4"), Ok(Number(0.4)));
2488 assert_eq!(from_str("0.4e5"), Ok(Number(0.4e5)));
2489 assert_eq!(from_str("0.4e+15"), Ok(Number(0.4e15)));
2490 assert_eq!(from_str("0.4e-01"), Ok(Number(0.4e-01)));
2491 assert_eq!(from_str(" 3 "), Ok(Number(3.0)));
2495 fn test_decode_numbers() {
2496 let v: f64 = super::decode("3").unwrap();
2499 let v: f64 = super::decode("3.1").unwrap();
2502 let v: f64 = super::decode("-1.2").unwrap();
2503 assert_eq!(v, -1.2);
2505 let v: f64 = super::decode("0.4").unwrap();
2508 let v: f64 = super::decode("0.4e5").unwrap();
2509 assert_eq!(v, 0.4e5);
2511 let v: f64 = super::decode("0.4e15").unwrap();
2512 assert_eq!(v, 0.4e15);
2514 let v: f64 = super::decode("0.4e-01").unwrap();
2515 assert_eq!(v, 0.4e-01);
2519 fn test_read_str() {
2520 assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2)));
2521 assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
2523 assert_eq!(from_str("\"\""), Ok(String("".to_string())));
2524 assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
2525 assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
2526 assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
2527 assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
2528 assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
2529 assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
2530 assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
2531 assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u12ab".to_string())));
2532 assert_eq!(from_str("\"\\uAB12\""), Ok(String("\uAB12".to_string())));
2536 fn test_decode_str() {
2537 let s = [("\"\"", ""),
2540 ("\"\\b\"", "\x08"),
2544 ("\"\\u12ab\"", "\u12ab"),
2545 ("\"\\uAB12\"", "\uAB12")];
2547 for &(i, o) in s.iter() {
2548 let v: String = super::decode(i).unwrap();
2549 assert_eq!(v.as_slice(), o);
2554 fn test_read_list() {
2555 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
2556 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingList, 1, 3)));
2557 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
2558 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2559 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2561 assert_eq!(from_str("[]"), Ok(List(vec![])));
2562 assert_eq!(from_str("[ ]"), Ok(List(vec![])));
2563 assert_eq!(from_str("[true]"), Ok(List(vec![Boolean(true)])));
2564 assert_eq!(from_str("[ false ]"), Ok(List(vec![Boolean(false)])));
2565 assert_eq!(from_str("[null]"), Ok(List(vec![Null])));
2566 assert_eq!(from_str("[3, 1]"),
2567 Ok(List(vec![Number(3.0), Number(1.0)])));
2568 assert_eq!(from_str("\n[3, 2]\n"),
2569 Ok(List(vec![Number(3.0), Number(2.0)])));
2570 assert_eq!(from_str("[2, [4, 1]]"),
2571 Ok(List(vec![Number(2.0), List(vec![Number(4.0), Number(1.0)])])));
2575 fn test_decode_list() {
2576 let v: Vec<()> = super::decode("[]").unwrap();
2577 assert_eq!(v, vec![]);
2579 let v: Vec<()> = super::decode("[null]").unwrap();
2580 assert_eq!(v, vec![()]);
2582 let v: Vec<bool> = super::decode("[true]").unwrap();
2583 assert_eq!(v, vec![true]);
2585 let v: Vec<int> = super::decode("[3, 1]").unwrap();
2586 assert_eq!(v, vec![3, 1]);
2588 let v: Vec<Vec<uint>> = super::decode("[[3], [1, 2]]").unwrap();
2589 assert_eq!(v, vec![vec![3], vec![1, 2]]);
2593 fn test_read_object() {
2594 assert_eq!(from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
2595 assert_eq!(from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
2596 assert_eq!(from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2)));
2597 assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
2598 assert_eq!(from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
2599 assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
2601 assert_eq!(from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6)));
2602 assert_eq!(from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6)));
2603 assert_eq!(from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
2604 assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8)));
2605 assert_eq!(from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
2607 assert_eq!(from_str("{}").unwrap(), mk_object([]));
2608 assert_eq!(from_str("{\"a\": 3}").unwrap(),
2609 mk_object([("a".to_string(), Number(3.0))]));
2611 assert_eq!(from_str(
2612 "{ \"a\": null, \"b\" : true }").unwrap(),
2614 ("a".to_string(), Null),
2615 ("b".to_string(), Boolean(true))]));
2616 assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
2618 ("a".to_string(), Null),
2619 ("b".to_string(), Boolean(true))]));
2620 assert_eq!(from_str(
2621 "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
2623 ("a".to_string(), Number(1.0)),
2624 ("b".to_string(), List(vec![Boolean(true)]))
2626 assert_eq!(from_str(
2632 { \"c\": {\"d\": null} } \
2636 ("a".to_string(), Number(1.0)),
2637 ("b".to_string(), List(vec![
2639 String("foo\nbar".to_string()),
2641 ("c".to_string(), mk_object([("d".to_string(), Null)]))
2648 fn test_decode_struct() {
2651 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
2655 let v: Outer = super::decode(s).unwrap();
2660 Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
2666 #[deriving(Decodable)]
2667 struct FloatStruct {
2672 fn test_decode_struct_with_nan() {
2673 let s = "{\"f\":null,\"a\":[null,123]}";
2674 let obj: FloatStruct = super::decode(s).unwrap();
2675 assert!(obj.f.is_nan());
2676 assert!(obj.a.get(0).is_nan());
2677 assert_eq!(obj.a.get(1), &123f64);
2681 fn test_decode_option() {
2682 let value: Option<String> = super::decode("null").unwrap();
2683 assert_eq!(value, None);
2685 let value: Option<String> = super::decode("\"jodhpurs\"").unwrap();
2686 assert_eq!(value, Some("jodhpurs".to_string()));
2690 fn test_decode_enum() {
2691 let value: Animal = super::decode("\"Dog\"").unwrap();
2692 assert_eq!(value, Dog);
2694 let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
2695 let value: Animal = super::decode(s).unwrap();
2696 assert_eq!(value, Frog("Henry".to_string(), 349));
2700 fn test_decode_map() {
2701 let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
2702 \"fields\":[\"Henry\", 349]}}";
2703 let mut map: TreeMap<String, Animal> = super::decode(s).unwrap();
2705 assert_eq!(map.pop(&"a".to_string()), Some(Dog));
2706 assert_eq!(map.pop(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
2710 fn test_multiline_errors() {
2711 assert_eq!(from_str("{\n \"foo\":\n \"bar\""),
2712 Err(SyntaxError(EOFWhileParsingObject, 3u, 8u)));
2715 #[deriving(Decodable)]
2717 struct DecodeStruct {
2721 w: Vec<DecodeStruct>
2723 #[deriving(Decodable)]
2728 fn check_err<T: Decodable<Decoder, DecoderError>>(to_parse: &'static str,
2729 expected: DecoderError) {
2730 let res: DecodeResult<T> = match from_str(to_parse) {
2731 Err(e) => Err(ParseError(e)),
2732 Ok(json) => Decodable::decode(&mut Decoder::new(json))
2735 Ok(_) => fail!("`{}` parsed & decoded ok, expecting error `{}`",
2736 to_parse, expected),
2737 Err(ParseError(e)) => fail!("`{}` is not valid json: {}",
2740 assert_eq!(e, expected);
2745 fn test_decode_errors_struct() {
2746 check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string()));
2747 check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
2748 ExpectedError("Number".to_string(), "true".to_string()));
2749 check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
2750 ExpectedError("Boolean".to_string(), "[]".to_string()));
2751 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
2752 ExpectedError("String".to_string(), "{}".to_string()));
2753 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
2754 ExpectedError("List".to_string(), "null".to_string()));
2755 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
2756 MissingFieldError("w".to_string()));
2759 fn test_decode_errors_enum() {
2760 check_err::<DecodeEnum>("{}",
2761 MissingFieldError("variant".to_string()));
2762 check_err::<DecodeEnum>("{\"variant\": 1}",
2763 ExpectedError("String".to_string(), "1".to_string()));
2764 check_err::<DecodeEnum>("{\"variant\": \"A\"}",
2765 MissingFieldError("fields".to_string()));
2766 check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
2767 ExpectedError("List".to_string(), "null".to_string()));
2768 check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
2769 UnknownVariantError("C".to_string()));
2774 let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
2775 let found_str = json_value.find(&"dog".to_string());
2776 assert!(found_str.is_some() && found_str.unwrap().as_string().unwrap() == "cat");
2780 fn test_find_path(){
2781 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
2782 let found_str = json_value.find_path(&[&"dog".to_string(),
2783 &"cat".to_string(), &"mouse".to_string()]);
2784 assert!(found_str.is_some() && found_str.unwrap().as_string().unwrap() == "cheese");
2789 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
2790 let found_str = json_value.search(&"mouse".to_string()).and_then(|j| j.as_string());
2791 assert!(found_str.is_some());
2792 assert!(found_str.unwrap() == "cheese");
2796 fn test_is_object(){
2797 let json_value = from_str("{}").unwrap();
2798 assert!(json_value.is_object());
2802 fn test_as_object(){
2803 let json_value = from_str("{}").unwrap();
2804 let json_object = json_value.as_object();
2805 assert!(json_object.is_some());
2810 let json_value = from_str("[1, 2, 3]").unwrap();
2811 assert!(json_value.is_list());
2816 let json_value = from_str("[1, 2, 3]").unwrap();
2817 let json_list = json_value.as_list();
2818 let expected_length = 3;
2819 assert!(json_list.is_some() && json_list.unwrap().len() == expected_length);
2823 fn test_is_string(){
2824 let json_value = from_str("\"dog\"").unwrap();
2825 assert!(json_value.is_string());
2829 fn test_as_string(){
2830 let json_value = from_str("\"dog\"").unwrap();
2831 let json_str = json_value.as_string();
2832 let expected_str = "dog";
2833 assert_eq!(json_str, Some(expected_str));
2837 fn test_is_number(){
2838 let json_value = from_str("12").unwrap();
2839 assert!(json_value.is_number());
2843 fn test_as_number(){
2844 let json_value = from_str("12").unwrap();
2845 let json_num = json_value.as_number();
2846 let expected_num = 12f64;
2847 assert!(json_num.is_some() && json_num.unwrap() == expected_num);
2851 fn test_is_boolean(){
2852 let json_value = from_str("false").unwrap();
2853 assert!(json_value.is_boolean());
2857 fn test_as_boolean(){
2858 let json_value = from_str("false").unwrap();
2859 let json_bool = json_value.as_boolean();
2860 let expected_bool = false;
2861 assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
2866 let json_value = from_str("null").unwrap();
2867 assert!(json_value.is_null());
2872 let json_value = from_str("null").unwrap();
2873 let json_null = json_value.as_null();
2874 let expected_null = ();
2875 assert!(json_null.is_some() && json_null.unwrap() == expected_null);
2879 fn test_encode_hashmap_with_numeric_key() {
2880 use std::str::from_utf8;
2881 use std::io::Writer;
2882 use std::io::MemWriter;
2883 use std::collections::HashMap;
2884 let mut hm: HashMap<uint, bool> = HashMap::new();
2886 let mut mem_buf = MemWriter::new();
2888 let mut encoder = Encoder::new(&mut mem_buf as &mut io::Writer);
2889 hm.encode(&mut encoder).unwrap();
2891 let bytes = mem_buf.unwrap();
2892 let json_str = from_utf8(bytes.as_slice()).unwrap();
2893 match from_str(json_str) {
2894 Err(_) => fail!("Unable to parse json_str: {}", json_str),
2895 _ => {} // it parsed and we are good to go
2899 fn test_prettyencode_hashmap_with_numeric_key() {
2900 use std::str::from_utf8;
2901 use std::io::Writer;
2902 use std::io::MemWriter;
2903 use std::collections::HashMap;
2904 let mut hm: HashMap<uint, bool> = HashMap::new();
2906 let mut mem_buf = MemWriter::new();
2908 let mut encoder = PrettyEncoder::new(&mut mem_buf as &mut io::Writer);
2909 hm.encode(&mut encoder).unwrap()
2911 let bytes = mem_buf.unwrap();
2912 let json_str = from_utf8(bytes.as_slice()).unwrap();
2913 match from_str(json_str) {
2914 Err(_) => fail!("Unable to parse json_str: {}", json_str),
2915 _ => {} // it parsed and we are good to go
2919 fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
2920 use std::collections::HashMap;
2922 let json_str = "{\"1\":true}";
2923 let json_obj = match from_str(json_str) {
2924 Err(_) => fail!("Unable to parse json_str: {}", json_str),
2927 let mut decoder = Decoder::new(json_obj);
2928 let _hm: HashMap<uint, bool> = Decodable::decode(&mut decoder).unwrap();
2931 fn assert_stream_equal(src: &str,
2932 expected: Vec<(JsonEvent, Vec<StackElement>)>) {
2933 let mut parser = Parser::new(src.chars());
2936 let evt = match parser.next() {
2940 let (ref expected_evt, ref expected_stack) = *expected.get(i);
2941 if !parser.stack().is_equal_to(expected_stack.as_slice()) {
2942 fail!("Parser stack is not equal to {}", expected_stack);
2944 assert_eq!(&evt, expected_evt);
2949 #[ignore(cfg(target_word_size = "32"))] // FIXME(#14064)
2950 fn test_streaming_parser() {
2951 assert_stream_equal(
2952 r#"{ "foo":"bar", "array" : [0, 1, 2,3 ,4,5], "idents":[null,true,false]}"#,
2954 (ObjectStart, vec![]),
2955 (StringValue("bar".to_string()), vec![Key("foo")]),
2956 (ListStart, vec![Key("array")]),
2957 (NumberValue(0.0), vec![Key("array"), Index(0)]),
2958 (NumberValue(1.0), vec![Key("array"), Index(1)]),
2959 (NumberValue(2.0), vec![Key("array"), Index(2)]),
2960 (NumberValue(3.0), vec![Key("array"), Index(3)]),
2961 (NumberValue(4.0), vec![Key("array"), Index(4)]),
2962 (NumberValue(5.0), vec![Key("array"), Index(5)]),
2963 (ListEnd, vec![Key("array")]),
2964 (ListStart, vec![Key("idents")]),
2965 (NullValue, vec![Key("idents"), Index(0)]),
2966 (BooleanValue(true), vec![Key("idents"), Index(1)]),
2967 (BooleanValue(false), vec![Key("idents"), Index(2)]),
2968 (ListEnd, vec![Key("idents")]),
2969 (ObjectEnd, vec![]),
2973 fn last_event(src: &str) -> JsonEvent {
2974 let mut parser = Parser::new(src.chars());
2975 let mut evt = NullValue;
2977 evt = match parser.next() {
2984 #[ignore(cfg(target_word_size = "32"))] // FIXME(#14064)
2985 fn test_read_object_streaming() {
2986 assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
2987 assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2)));
2988 assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
2989 assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
2990 assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
2992 assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6)));
2993 assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6)));
2994 assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
2995 assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8)));
2996 assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
2998 assert_stream_equal(
3000 vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]
3002 assert_stream_equal(
3005 (ObjectStart, vec![]),
3006 (NumberValue(3.0), vec![Key("a")]),
3007 (ObjectEnd, vec![]),
3010 assert_stream_equal(
3011 "{ \"a\": null, \"b\" : true }",
3013 (ObjectStart, vec![]),
3014 (NullValue, vec![Key("a")]),
3015 (BooleanValue(true), vec![Key("b")]),
3016 (ObjectEnd, vec![]),
3019 assert_stream_equal(
3020 "{\"a\" : 1.0 ,\"b\": [ true ]}",
3022 (ObjectStart, vec![]),
3023 (NumberValue(1.0), vec![Key("a")]),
3024 (ListStart, vec![Key("b")]),
3025 (BooleanValue(true),vec![Key("b"), Index(0)]),
3026 (ListEnd, vec![Key("b")]),
3027 (ObjectEnd, vec![]),
3030 assert_stream_equal(
3036 { "c": {"d": null} }
3040 (ObjectStart, vec![]),
3041 (NumberValue(1.0), vec![Key("a")]),
3042 (ListStart, vec![Key("b")]),
3043 (BooleanValue(true), vec![Key("b"), Index(0)]),
3044 (StringValue("foo\nbar".to_string()), vec![Key("b"), Index(1)]),
3045 (ObjectStart, vec![Key("b"), Index(2)]),
3046 (ObjectStart, vec![Key("b"), Index(2), Key("c")]),
3047 (NullValue, vec![Key("b"), Index(2), Key("c"), Key("d")]),
3048 (ObjectEnd, vec![Key("b"), Index(2), Key("c")]),
3049 (ObjectEnd, vec![Key("b"), Index(2)]),
3050 (ListEnd, vec![Key("b")]),
3051 (ObjectEnd, vec![]),
3056 #[ignore(cfg(target_word_size = "32"))] // FIXME(#14064)
3057 fn test_read_list_streaming() {
3058 assert_stream_equal(
3061 (ListStart, vec![]),
3065 assert_stream_equal(
3068 (ListStart, vec![]),
3072 assert_stream_equal(
3075 (ListStart, vec![]),
3076 (BooleanValue(true), vec![Index(0)]),
3080 assert_stream_equal(
3083 (ListStart, vec![]),
3084 (BooleanValue(false), vec![Index(0)]),
3088 assert_stream_equal(
3091 (ListStart, vec![]),
3092 (NullValue, vec![Index(0)]),
3096 assert_stream_equal(
3099 (ListStart, vec![]),
3100 (NumberValue(3.0), vec![Index(0)]),
3101 (NumberValue(1.0), vec![Index(1)]),
3105 assert_stream_equal(
3108 (ListStart, vec![]),
3109 (NumberValue(3.0), vec![Index(0)]),
3110 (NumberValue(2.0), vec![Index(1)]),
3114 assert_stream_equal(
3117 (ListStart, vec![]),
3118 (NumberValue(2.0), vec![Index(0)]),
3119 (ListStart, vec![Index(1)]),
3120 (NumberValue(4.0), vec![Index(1), Index(0)]),
3121 (NumberValue(1.0), vec![Index(1), Index(1)]),
3122 (ListEnd, vec![Index(1)]),
3127 assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2)));
3129 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
3130 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingList, 1, 3)));
3131 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
3132 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3133 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3137 fn test_trailing_characters_streaming() {
3138 assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3139 assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3140 assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
3141 assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2)));
3142 assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3143 assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3146 fn test_read_identifiers_streaming() {
3147 assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
3148 assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
3149 assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));
3151 assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3152 assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3153 assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3154 assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3155 assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3156 assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3)));
3161 let mut stack = Stack::new();
3163 assert!(stack.is_empty());
3164 assert!(stack.len() == 0);
3165 assert!(!stack.last_is_index());
3167 stack.push_index(0);
3170 assert!(stack.len() == 1);
3171 assert!(stack.is_equal_to([Index(1)]));
3172 assert!(stack.starts_with([Index(1)]));
3173 assert!(stack.ends_with([Index(1)]));
3174 assert!(stack.last_is_index());
3175 assert!(stack.get(0) == Index(1));
3177 stack.push_key("foo".to_string());
3179 assert!(stack.len() == 2);
3180 assert!(stack.is_equal_to([Index(1), Key("foo")]));
3181 assert!(stack.starts_with([Index(1), Key("foo")]));
3182 assert!(stack.starts_with([Index(1)]));
3183 assert!(stack.ends_with([Index(1), Key("foo")]));
3184 assert!(stack.ends_with([Key("foo")]));
3185 assert!(!stack.last_is_index());
3186 assert!(stack.get(0) == Index(1));
3187 assert!(stack.get(1) == Key("foo"));
3189 stack.push_key("bar".to_string());
3191 assert!(stack.len() == 3);
3192 assert!(stack.is_equal_to([Index(1), Key("foo"), Key("bar")]));
3193 assert!(stack.starts_with([Index(1)]));
3194 assert!(stack.starts_with([Index(1), Key("foo")]));
3195 assert!(stack.starts_with([Index(1), Key("foo"), Key("bar")]));
3196 assert!(stack.ends_with([Key("bar")]));
3197 assert!(stack.ends_with([Key("foo"), Key("bar")]));
3198 assert!(stack.ends_with([Index(1), Key("foo"), Key("bar")]));
3199 assert!(!stack.last_is_index());
3200 assert!(stack.get(0) == Index(1));
3201 assert!(stack.get(1) == Key("foo"));
3202 assert!(stack.get(2) == Key("bar"));
3206 assert!(stack.len() == 2);
3207 assert!(stack.is_equal_to([Index(1), Key("foo")]));
3208 assert!(stack.starts_with([Index(1), Key("foo")]));
3209 assert!(stack.starts_with([Index(1)]));
3210 assert!(stack.ends_with([Index(1), Key("foo")]));
3211 assert!(stack.ends_with([Key("foo")]));
3212 assert!(!stack.last_is_index());
3213 assert!(stack.get(0) == Index(1));
3214 assert!(stack.get(1) == Key("foo"));
3219 use std::collections::{HashMap,TreeMap};
3222 let list2 = List(vec!(Number(1.0_f64), Number(2.0_f64)));
3223 let list3 = List(vec!(Number(1.0f64), Number(2.0f64), Number(3.0f64)));
3225 let mut tree_map = TreeMap::new();
3226 tree_map.insert("a".to_string(), Number(1.0_f64));
3227 tree_map.insert("b".to_string(), Number(2.0_f64));
3231 assert_eq!(list2.to_json(), list2);
3232 assert_eq!(object.to_json(), object);
3233 assert_eq!(3_i.to_json(), Number(3.0_f64));
3234 assert_eq!(4_i8.to_json(), Number(4.0_f64));
3235 assert_eq!(5_i16.to_json(), Number(5.0_f64));
3236 assert_eq!(6_i32.to_json(), Number(6.0_f64));
3237 assert_eq!(7_i64.to_json(), Number(7.0_f64));
3238 assert_eq!(8_u.to_json(), Number(8.0_f64));
3239 assert_eq!(9_u8.to_json(), Number(9.0_f64));
3240 assert_eq!(10_u16.to_json(), Number(10.0_f64));
3241 assert_eq!(11_u32.to_json(), Number(11.0_f64));
3242 assert_eq!(12_u64.to_json(), Number(12.0_f64));
3243 assert_eq!(13.0_f32.to_json(), Number(13.0_f64));
3244 assert_eq!(14.0_f64.to_json(), Number(14.0_f64));
3245 assert_eq!(().to_json(), Null);
3246 assert_eq!(f32::INFINITY.to_json(), Null);
3247 assert_eq!(f64::NAN.to_json(), Null);
3248 assert_eq!(true.to_json(), Boolean(true));
3249 assert_eq!(false.to_json(), Boolean(false));
3250 assert_eq!("abc".to_string().to_json(), String("abc".to_string()));
3251 assert_eq!((1i, 2i).to_json(), list2);
3252 assert_eq!((1i, 2i, 3i).to_json(), list3);
3253 assert_eq!([1i, 2].to_json(), list2);
3254 assert_eq!((&[1i, 2, 3]).to_json(), list3);
3255 assert_eq!((vec![1i, 2]).to_json(), list2);
3256 assert_eq!(vec!(1i, 2i, 3i).to_json(), list3);
3257 let mut tree_map = TreeMap::new();
3258 tree_map.insert("a".to_string(), 1i);
3259 tree_map.insert("b".to_string(), 2);
3260 assert_eq!(tree_map.to_json(), object);
3261 let mut hash_map = HashMap::new();
3262 hash_map.insert("a".to_string(), 1i);
3263 hash_map.insert("b".to_string(), 2);
3264 assert_eq!(hash_map.to_json(), object);
3265 assert_eq!(Some(15i).to_json(), Number(15f64));
3266 assert_eq!(None::<int>.to_json(), Null);
3270 fn bench_streaming_small(b: &mut Bencher) {
3272 let mut parser = Parser::new(
3278 { "c": {"d": null} }
3283 match parser.next() {
3291 fn bench_small(b: &mut Bencher) {
3293 let _ = from_str(r#"{
3298 { "c": {"d": null} }
3304 fn big_json() -> String {
3305 let mut src = "[\n".to_string();
3306 for _ in range(0i, 500) {
3307 src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \
3310 src.push_str("{}]");
3315 fn bench_streaming_large(b: &mut Bencher) {
3316 let src = big_json();
3318 let mut parser = Parser::new(src.as_slice().chars());
3320 match parser.next() {
3328 fn bench_large(b: &mut Bencher) {
3329 let src = big_json();
3330 b.iter( || { let _ = from_str(src.as_slice()); });