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_docs)]
17 //! JSON parsing and serialization
21 //! JSON (JavaScript Object Notation) is a way to write data in Javascript.
22 //! Like XML, it allows to encode structured data in a text format that can be easily read by humans
23 //! Its simple syntax and native compatibility with JavaScript have made it a widely used format.
25 //! Data types that can be encoded are JavaScript types (see the `Json` enum for more details):
27 //! * `Boolean`: equivalent to rust's `bool`
28 //! * `Number`: equivalent to rust's `f64`
29 //! * `String`: equivalent to rust's `String`
30 //! * `Array`: equivalent to rust's `Vec<T>`, but also allowing objects of different types in the
32 //! * `Object`: equivalent to rust's `Treemap<String, json::Json>`
35 //! An object is a series of string keys mapping to values, in `"key": value` format.
36 //! Arrays are enclosed in square brackets ([ ... ]) and objects in curly brackets ({ ... }).
37 //! A simple JSON document encoding a person, his/her age, address and phone numbers could look like
41 //! "FirstName": "John",
42 //! "LastName": "Doe",
45 //! "Street": "Downing Street 10",
47 //! "Country": "Great Britain"
56 //! # Rust Type-based Encoding and Decoding
58 //! Rust provides a mechanism for low boilerplate encoding & decoding of values to and from JSON via
59 //! the serialization API.
60 //! To be able to encode a piece of data, it must implement the `serialize::Encodable` trait.
61 //! To be able to decode a piece of data, it must implement the `serialize::Decodable` trait.
62 //! The Rust compiler provides an annotation to automatically generate the code for these traits:
63 //! `#[deriving(Decodable, Encodable)]`
65 //! The JSON API provides an enum `json::Json` and a trait `ToJson` to encode objects.
66 //! The `ToJson` trait provides a `to_json` method to convert an object into a `json::Json` value.
67 //! A `json::Json` value can be encoded as a string or buffer using the functions described above.
68 //! You can also use the `json::Encoder` object, which implements the `Encoder` trait.
70 //! When using `ToJson` the `Encodable` trait implementation is not mandatory.
74 //! ## Using Autoserialization
76 //! Create a struct called `TestStruct` and serialize and deserialize it to and from JSON using the
77 //! serialization API, using the derived serialization code.
80 //! extern crate serialize;
81 //! use serialize::json;
83 //! // Automatically generate `Decodable` and `Encodable` trait implementations
84 //! #[deriving(Decodable, Encodable)]
85 //! pub struct TestStruct {
88 //! data_vector: Vec<u8>,
92 //! let object = TestStruct {
94 //! data_str: "toto".to_string(),
95 //! data_vector: vec![2,3,4,5],
98 //! // Serialize using `json::encode`
99 //! let encoded = json::encode(&object);
101 //! // Deserialize using `json::decode`
102 //! let decoded: TestStruct = json::decode(encoded.as_slice()).unwrap();
106 //! ## Using the `ToJson` trait
108 //! The examples above use the `ToJson` trait to generate the JSON string, which is required
109 //! for custom mappings.
111 //! ### Simple example of `ToJson` usage
114 //! extern crate serialize;
115 //! use serialize::json::{mod, ToJson, Json};
117 //! // A custom data structure
118 //! struct ComplexNum {
123 //! // JSON value representation
124 //! impl ToJson for ComplexNum {
125 //! fn to_json(&self) -> Json {
126 //! Json::String(format!("{}+{}i", self.a, self.b))
130 //! // Only generate `Encodable` trait implementation
131 //! #[deriving(Encodable)]
132 //! pub struct ComplexNumRecord {
139 //! let num = ComplexNum { a: 0.0001, b: 12.539 };
140 //! let data: String = json::encode(&ComplexNumRecord{
142 //! dsc: "test".to_string(),
143 //! val: num.to_json(),
145 //! println!("data: {}", data);
146 //! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539j"};
150 //! ### Verbose example of `ToJson` usage
153 //! extern crate serialize;
154 //! use std::collections::TreeMap;
155 //! use serialize::json::{mod, Json, ToJson};
157 //! // Only generate `Decodable` trait implementation
158 //! #[deriving(Decodable)]
159 //! pub struct TestStruct {
161 //! data_str: String,
162 //! data_vector: Vec<u8>,
165 //! // Specify encoding method manually
166 //! impl ToJson for TestStruct {
167 //! fn to_json(&self) -> Json {
168 //! let mut d = TreeMap::new();
169 //! // All standard types implement `to_json()`, so use it
170 //! d.insert("data_int".to_string(), self.data_int.to_json());
171 //! d.insert("data_str".to_string(), self.data_str.to_json());
172 //! d.insert("data_vector".to_string(), self.data_vector.to_json());
178 //! // Serialize using `ToJson`
179 //! let input_data = TestStruct {
181 //! data_str: "toto".to_string(),
182 //! data_vector: vec![2,3,4,5],
184 //! let json_obj: Json = input_data.to_json();
185 //! let json_str: String = json_obj.to_string();
187 //! // Deserialize like before
188 //! let decoded: TestStruct = json::decode(json_str.as_slice()).unwrap();
192 use self::JsonEvent::*;
193 use self::StackElement::*;
194 use self::ErrorCode::*;
195 use self::ParserError::*;
196 use self::DecoderError::*;
197 use self::ParserState::*;
198 use self::InternalStackElement::*;
201 use std::collections::{HashMap, TreeMap};
202 use std::{char, f64, fmt, io, num, str};
203 use std::mem::{swap, transmute};
204 use std::num::{Float, FPNaN, FPInfinite, Int};
205 use std::str::{FromStr, ScalarValue};
212 /// Represents a json value
213 #[deriving(Clone, PartialEq, PartialOrd)]
218 String(string::String),
221 Object(self::Object),
225 pub type Array = Vec<Json>;
226 pub type Object = TreeMap<string::String, Json>;
228 /// The errors that can arise while parsing a JSON stream.
229 #[deriving(Clone, PartialEq)]
233 EOFWhileParsingObject,
234 EOFWhileParsingArray,
235 EOFWhileParsingValue,
236 EOFWhileParsingString,
242 InvalidUnicodeCodePoint,
243 LoneLeadingSurrogateInHexEscape,
244 UnexpectedEndOfHexEscape,
250 #[deriving(Clone, PartialEq, Show)]
251 pub enum ParserError {
253 SyntaxError(ErrorCode, uint, uint),
254 IoError(io::IoErrorKind, &'static str),
257 // Builder and Parser have the same errors.
258 pub type BuilderError = ParserError;
260 #[deriving(Clone, PartialEq, Show)]
261 pub enum DecoderError {
262 ParseError(ParserError),
263 ExpectedError(string::String, string::String),
264 MissingFieldError(string::String),
265 UnknownVariantError(string::String),
266 ApplicationError(string::String)
269 /// Returns a readable error string for a given error code.
270 pub fn error_str(error: ErrorCode) -> &'static str {
272 InvalidSyntax => "invalid syntax",
273 InvalidNumber => "invalid number",
274 EOFWhileParsingObject => "EOF While parsing object",
275 EOFWhileParsingArray => "EOF While parsing array",
276 EOFWhileParsingValue => "EOF While parsing value",
277 EOFWhileParsingString => "EOF While parsing string",
278 KeyMustBeAString => "key must be a string",
279 ExpectedColon => "expected `:`",
280 TrailingCharacters => "trailing characters",
281 TrailingComma => "trailing comma",
282 InvalidEscape => "invalid escape",
283 UnrecognizedHex => "invalid \\u escape (unrecognized hex)",
284 NotFourDigit => "invalid \\u escape (not four digits)",
285 NotUtf8 => "contents not utf-8",
286 InvalidUnicodeCodePoint => "invalid Unicode code point",
287 LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
288 UnexpectedEndOfHexEscape => "unexpected end of hex escape",
292 /// Shortcut function to decode a JSON `&str` into an object
293 pub fn decode<T: ::Decodable<Decoder, DecoderError>>(s: &str) -> DecodeResult<T> {
294 let json = match from_str(s) {
296 Err(e) => return Err(ParseError(e))
299 let mut decoder = Decoder::new(json);
300 ::Decodable::decode(&mut decoder)
303 /// Shortcut function to encode a `T` into a JSON `String`
304 pub fn encode<'a, T: Encodable<Encoder<'a>, io::IoError>>(object: &T) -> string::String {
305 let buff = Encoder::buffer_encode(object);
306 string::String::from_utf8(buff).unwrap()
309 impl fmt::Show for ErrorCode {
310 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
311 error_str(*self).fmt(f)
315 fn io_error_to_error(io: io::IoError) -> ParserError {
316 IoError(io.kind, io.desc)
319 impl std::error::Error for DecoderError {
320 fn description(&self) -> &str { "decoder error" }
321 fn detail(&self) -> Option<std::string::String> { Some(self.to_string()) }
324 pub type EncodeResult = io::IoResult<()>;
325 pub type DecodeResult<T> = Result<T, DecoderError>;
327 pub fn escape_bytes(wr: &mut io::Writer, bytes: &[u8]) -> Result<(), io::IoError> {
328 try!(wr.write_str("\""));
332 for (i, byte) in bytes.iter().enumerate() {
333 let escaped = match *byte {
345 try!(wr.write(bytes[start..i]));
348 try!(wr.write_str(escaped));
353 if start != bytes.len() {
354 try!(wr.write(bytes[start..]));
360 fn escape_str(writer: &mut io::Writer, v: &str) -> Result<(), io::IoError> {
361 escape_bytes(writer, v.as_bytes())
364 fn escape_char(writer: &mut io::Writer, v: char) -> Result<(), io::IoError> {
365 let mut buf = [0, .. 4];
366 v.encode_utf8(&mut buf);
367 escape_bytes(writer, &mut buf)
370 fn spaces(wr: &mut io::Writer, mut n: uint) -> Result<(), io::IoError> {
371 const LEN: uint = 16;
372 static BUF: [u8, ..LEN] = [b' ', ..LEN];
375 try!(wr.write(&BUF));
386 fn fmt_number_or_null(v: f64) -> string::String {
388 FPNaN | FPInfinite => string::String::from_str("null"),
389 _ if v.fract() != 0f64 => f64::to_str_digits(v, 6u),
390 _ => f64::to_str_digits(v, 6u) + ".0",
394 /// A structure for implementing serialization to JSON.
395 pub struct Encoder<'a> {
396 writer: &'a mut (io::Writer+'a),
399 impl<'a> Encoder<'a> {
400 /// Creates a new JSON encoder whose output will be written to the writer
402 pub fn new(writer: &'a mut io::Writer) -> Encoder<'a> {
403 Encoder { writer: writer }
406 /// Encode the specified struct into a json [u8]
407 pub fn buffer_encode<T:Encodable<Encoder<'a>, io::IoError>>(object: &T) -> Vec<u8> {
408 //Serialize the object in a string using a writer
409 let mut m = Vec::new();
410 // FIXME(14302) remove the transmute and unsafe block.
412 let mut encoder = Encoder::new(&mut m as &mut io::Writer);
413 // Vec<u8> never Errs
414 let _ = object.encode(transmute(&mut encoder));
420 impl<'a> ::Encoder<io::IoError> for Encoder<'a> {
421 fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
423 fn emit_uint(&mut self, v: uint) -> EncodeResult { write!(self.writer, "{}", v) }
424 fn emit_u64(&mut self, v: u64) -> EncodeResult { write!(self.writer, "{}", v) }
425 fn emit_u32(&mut self, v: u32) -> EncodeResult { write!(self.writer, "{}", v) }
426 fn emit_u16(&mut self, v: u16) -> EncodeResult { write!(self.writer, "{}", v) }
427 fn emit_u8(&mut self, v: u8) -> EncodeResult { write!(self.writer, "{}", v) }
429 fn emit_int(&mut self, v: int) -> EncodeResult { write!(self.writer, "{}", v) }
430 fn emit_i64(&mut self, v: i64) -> EncodeResult { write!(self.writer, "{}", v) }
431 fn emit_i32(&mut self, v: i32) -> EncodeResult { write!(self.writer, "{}", v) }
432 fn emit_i16(&mut self, v: i16) -> EncodeResult { write!(self.writer, "{}", v) }
433 fn emit_i8(&mut self, v: i8) -> EncodeResult { write!(self.writer, "{}", v) }
435 fn emit_bool(&mut self, v: bool) -> EncodeResult {
437 write!(self.writer, "true")
439 write!(self.writer, "false")
443 fn emit_f64(&mut self, v: f64) -> EncodeResult {
444 write!(self.writer, "{}", fmt_number_or_null(v))
446 fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) }
448 fn emit_char(&mut self, v: char) -> EncodeResult {
449 escape_char(self.writer, v)
451 fn emit_str(&mut self, v: &str) -> EncodeResult {
452 escape_str(self.writer, v)
455 fn emit_enum(&mut self, _name: &str, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
459 fn emit_enum_variant(&mut self,
463 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
464 // enums are encoded as strings or objects
466 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
468 escape_str(self.writer, name)
470 try!(write!(self.writer, "{{\"variant\":"));
471 try!(escape_str(self.writer, name));
472 try!(write!(self.writer, ",\"fields\":["));
474 write!(self.writer, "]}}")
478 fn emit_enum_variant_arg(&mut self,
480 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
482 try!(write!(self.writer, ","));
487 fn emit_enum_struct_variant(&mut self,
491 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
492 self.emit_enum_variant(name, id, cnt, f)
495 fn emit_enum_struct_variant_field(&mut self,
498 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
499 self.emit_enum_variant_arg(idx, f)
502 fn emit_struct(&mut self,
505 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
506 try!(write!(self.writer, "{{"));
508 write!(self.writer, "}}")
511 fn emit_struct_field(&mut self,
514 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
515 if idx != 0 { try!(write!(self.writer, ",")); }
516 try!(escape_str(self.writer, name));
517 try!(write!(self.writer, ":"));
521 fn emit_tuple(&mut self, len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
522 self.emit_seq(len, f)
524 fn emit_tuple_arg(&mut self,
526 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
527 self.emit_seq_elt(idx, f)
530 fn emit_tuple_struct(&mut self,
533 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
534 self.emit_seq(len, f)
536 fn emit_tuple_struct_arg(&mut self,
538 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
539 self.emit_seq_elt(idx, f)
542 fn emit_option(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
545 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
546 fn emit_option_some(&mut self, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
550 fn emit_seq(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
551 try!(write!(self.writer, "["));
553 write!(self.writer, "]")
556 fn emit_seq_elt(&mut self, idx: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
558 try!(write!(self.writer, ","));
563 fn emit_map(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
564 try!(write!(self.writer, "{{"));
566 write!(self.writer, "}}")
569 fn emit_map_elt_key(&mut self,
571 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
572 if idx != 0 { try!(write!(self.writer, ",")) }
573 // ref #12967, make sure to wrap a key in double quotes,
574 // in the event that its of a type that omits them (eg numbers)
575 let mut buf = Vec::new();
576 // FIXME(14302) remove the transmute and unsafe block.
578 let mut check_encoder = Encoder::new(&mut buf);
579 try!(f(transmute(&mut check_encoder)));
581 let out = str::from_utf8(buf[]).unwrap();
582 let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
583 if needs_wrapping { try!(write!(self.writer, "\"")); }
585 if needs_wrapping { try!(write!(self.writer, "\"")); }
589 fn emit_map_elt_val(&mut self,
591 f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
592 try!(write!(self.writer, ":"));
597 /// Another encoder for JSON, but prints out human-readable JSON instead of
599 pub struct PrettyEncoder<'a> {
600 writer: &'a mut (io::Writer+'a),
605 impl<'a> PrettyEncoder<'a> {
606 /// Creates a new encoder whose output will be written to the specified writer
607 pub fn new<'a>(writer: &'a mut io::Writer) -> PrettyEncoder<'a> {
608 PrettyEncoder { writer: writer, curr_indent: 0, indent: 2, }
611 /// Set the number of spaces to indent for each level.
612 /// This is safe to set during encoding.
613 pub fn set_indent<'a>(&mut self, indent: uint) {
614 // self.indent very well could be 0 so we need to use checked division.
615 let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
616 self.indent = indent;
617 self.curr_indent = level * self.indent;
621 impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> {
622 fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") }
624 fn emit_uint(&mut self, v: uint) -> EncodeResult { write!(self.writer, "{}", v) }
625 fn emit_u64(&mut self, v: u64) -> EncodeResult { write!(self.writer, "{}", v) }
626 fn emit_u32(&mut self, v: u32) -> EncodeResult { write!(self.writer, "{}", v) }
627 fn emit_u16(&mut self, v: u16) -> EncodeResult { write!(self.writer, "{}", v) }
628 fn emit_u8(&mut self, v: u8) -> EncodeResult { write!(self.writer, "{}", v) }
630 fn emit_int(&mut self, v: int) -> EncodeResult { write!(self.writer, "{}", v) }
631 fn emit_i64(&mut self, v: i64) -> EncodeResult { write!(self.writer, "{}", v) }
632 fn emit_i32(&mut self, v: i32) -> EncodeResult { write!(self.writer, "{}", v) }
633 fn emit_i16(&mut self, v: i16) -> EncodeResult { write!(self.writer, "{}", v) }
634 fn emit_i8(&mut self, v: i8) -> EncodeResult { write!(self.writer, "{}", v) }
636 fn emit_bool(&mut self, v: bool) -> EncodeResult {
638 write!(self.writer, "true")
640 write!(self.writer, "false")
644 fn emit_f64(&mut self, v: f64) -> EncodeResult {
645 write!(self.writer, "{}", fmt_number_or_null(v))
647 fn emit_f32(&mut self, v: f32) -> EncodeResult {
648 self.emit_f64(v as f64)
651 fn emit_char(&mut self, v: char) -> EncodeResult {
652 escape_char(self.writer, v)
654 fn emit_str(&mut self, v: &str) -> EncodeResult {
655 escape_str(self.writer, v)
658 fn emit_enum(&mut self,
660 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
664 fn emit_enum_variant(&mut self,
668 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
670 escape_str(self.writer, name)
672 try!(write!(self.writer, "{{\n"));
673 self.curr_indent += self.indent;
674 try!(spaces(self.writer, self.curr_indent));
675 try!(write!(self.writer, "\"variant\": "));
676 try!(escape_str(self.writer, name));
677 try!(write!(self.writer, ",\n"));
678 try!(spaces(self.writer, self.curr_indent));
679 try!(write!(self.writer, "\"fields\": [\n"));
680 self.curr_indent += self.indent;
682 self.curr_indent -= self.indent;
683 try!(write!(self.writer, "\n"));
684 try!(spaces(self.writer, self.curr_indent));
685 self.curr_indent -= self.indent;
686 try!(write!(self.writer, "]\n"));
687 try!(spaces(self.writer, self.curr_indent));
688 write!(self.writer, "}}")
692 fn emit_enum_variant_arg(&mut self,
694 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
696 try!(write!(self.writer, ",\n"));
698 try!(spaces(self.writer, self.curr_indent));
702 fn emit_enum_struct_variant(&mut self,
706 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
707 self.emit_enum_variant(name, id, cnt, f)
710 fn emit_enum_struct_variant_field(&mut self,
713 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
714 self.emit_enum_variant_arg(idx, f)
718 fn emit_struct(&mut self,
721 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
723 write!(self.writer, "{{}}")
725 try!(write!(self.writer, "{{"));
726 self.curr_indent += self.indent;
728 self.curr_indent -= self.indent;
729 try!(write!(self.writer, "\n"));
730 try!(spaces(self.writer, self.curr_indent));
731 write!(self.writer, "}}")
735 fn emit_struct_field(&mut self,
738 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
740 try!(write!(self.writer, "\n"));
742 try!(write!(self.writer, ",\n"));
744 try!(spaces(self.writer, self.curr_indent));
745 try!(escape_str(self.writer, name));
746 try!(write!(self.writer, ": "));
750 fn emit_tuple(&mut self,
752 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
753 self.emit_seq(len, f)
755 fn emit_tuple_arg(&mut self,
757 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
758 self.emit_seq_elt(idx, f)
761 fn emit_tuple_struct(&mut self,
764 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
765 self.emit_seq(len, f)
767 fn emit_tuple_struct_arg(&mut self,
769 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
770 self.emit_seq_elt(idx, f)
773 fn emit_option(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
776 fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() }
777 fn emit_option_some(&mut self, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
781 fn emit_seq(&mut self,
783 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
785 write!(self.writer, "[]")
787 try!(write!(self.writer, "["));
788 self.curr_indent += self.indent;
790 self.curr_indent -= self.indent;
791 try!(write!(self.writer, "\n"));
792 try!(spaces(self.writer, self.curr_indent));
793 write!(self.writer, "]")
797 fn emit_seq_elt(&mut self,
799 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
801 try!(write!(self.writer, "\n"));
803 try!(write!(self.writer, ",\n"));
805 try!(spaces(self.writer, self.curr_indent));
809 fn emit_map(&mut self,
811 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
813 write!(self.writer, "{{}}")
815 try!(write!(self.writer, "{{"));
816 self.curr_indent += self.indent;
818 self.curr_indent -= self.indent;
819 try!(write!(self.writer, "\n"));
820 try!(spaces(self.writer, self.curr_indent));
821 write!(self.writer, "}}")
825 fn emit_map_elt_key(&mut self,
827 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
829 try!(write!(self.writer, "\n"));
831 try!(write!(self.writer, ",\n"));
833 try!(spaces(self.writer, self.curr_indent));
834 // ref #12967, make sure to wrap a key in double quotes,
835 // in the event that its of a type that omits them (eg numbers)
836 let mut buf = Vec::new();
837 // FIXME(14302) remove the transmute and unsafe block.
839 let mut check_encoder = PrettyEncoder::new(&mut buf);
840 try!(f(transmute(&mut check_encoder)));
842 let out = str::from_utf8(buf[]).unwrap();
843 let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
844 if needs_wrapping { try!(write!(self.writer, "\"")); }
846 if needs_wrapping { try!(write!(self.writer, "\"")); }
850 fn emit_map_elt_val(&mut self,
852 f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult {
853 try!(write!(self.writer, ": "));
858 impl<E: ::Encoder<S>, S> Encodable<E, S> for Json {
859 fn encode(&self, e: &mut E) -> Result<(), S> {
861 Json::I64(v) => v.encode(e),
862 Json::U64(v) => v.encode(e),
863 Json::F64(v) => v.encode(e),
864 Json::String(ref v) => v.encode(e),
865 Json::Boolean(v) => v.encode(e),
866 Json::Array(ref v) => v.encode(e),
867 Json::Object(ref v) => v.encode(e),
868 Json::Null => e.emit_nil(),
874 /// Encodes a json value into an io::writer. Uses a single line.
875 pub fn to_writer(&self, writer: &mut io::Writer) -> EncodeResult {
876 let mut encoder = Encoder::new(writer);
877 self.encode(&mut encoder)
880 /// Encodes a json value into an io::writer.
881 /// Pretty-prints in a more readable format.
882 pub fn to_pretty_writer(&self, writer: &mut io::Writer) -> EncodeResult {
883 let mut encoder = PrettyEncoder::new(writer);
884 self.encode(&mut encoder)
887 /// Encodes a json value into a string
888 pub fn to_pretty_str(&self) -> string::String {
889 let mut s = Vec::new();
890 self.to_pretty_writer(&mut s as &mut io::Writer).unwrap();
891 string::String::from_utf8(s).unwrap()
894 /// If the Json value is an Object, returns the value associated with the provided key.
895 /// Otherwise, returns None.
896 pub fn find<'a>(&'a self, key: &str) -> Option<&'a Json>{
898 &Json::Object(ref map) => map.get(key),
903 /// Attempts to get a nested Json Object for each key in `keys`.
904 /// If any key is found not to exist, find_path will return None.
905 /// Otherwise, it will return the Json value associated with the final key.
906 pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{
907 let mut target = self;
908 for key in keys.iter() {
909 match target.find(*key) {
910 Some(t) => { target = t; },
917 /// If the Json value is an Object, performs a depth-first search until
918 /// a value associated with the provided key is found. If no value is found
919 /// or the Json value is not an Object, returns None.
920 pub fn search<'a>(&'a self, key: &str) -> Option<&'a Json> {
922 &Json::Object(ref map) => {
924 Some(json_value) => Some(json_value),
926 for (_, v) in map.iter() {
927 match v.search(key) {
928 x if x.is_some() => return x,
940 /// Returns true if the Json value is an Object. Returns false otherwise.
941 pub fn is_object<'a>(&'a self) -> bool {
942 self.as_object().is_some()
945 /// If the Json value is an Object, returns the associated TreeMap.
946 /// Returns None otherwise.
947 pub fn as_object<'a>(&'a self) -> Option<&'a Object> {
949 &Json::Object(ref map) => Some(map),
954 /// Returns true if the Json value is an Array. Returns false otherwise.
955 pub fn is_array<'a>(&'a self) -> bool {
956 self.as_array().is_some()
959 /// If the Json value is an Array, returns the associated vector.
960 /// Returns None otherwise.
961 pub fn as_array<'a>(&'a self) -> Option<&'a Array> {
963 &Json::Array(ref array) => Some(&*array),
968 /// Returns true if the Json value is a String. Returns false otherwise.
969 pub fn is_string<'a>(&'a self) -> bool {
970 self.as_string().is_some()
973 /// If the Json value is a String, returns the associated str.
974 /// Returns None otherwise.
975 pub fn as_string<'a>(&'a self) -> Option<&'a str> {
977 Json::String(ref s) => Some(s.as_slice()),
982 /// Returns true if the Json value is a Number. Returns false otherwise.
983 pub fn is_number(&self) -> bool {
985 Json::I64(_) | Json::U64(_) | Json::F64(_) => true,
990 /// Returns true if the Json value is a i64. Returns false otherwise.
991 pub fn is_i64(&self) -> bool {
993 Json::I64(_) => true,
998 /// Returns true if the Json value is a u64. Returns false otherwise.
999 pub fn is_u64(&self) -> bool {
1001 Json::U64(_) => true,
1006 /// Returns true if the Json value is a f64. Returns false otherwise.
1007 pub fn is_f64(&self) -> bool {
1009 Json::F64(_) => true,
1014 /// If the Json value is a number, return or cast it to a i64.
1015 /// Returns None otherwise.
1016 pub fn as_i64(&self) -> Option<i64> {
1018 Json::I64(n) => Some(n),
1019 Json::U64(n) => num::cast(n),
1024 /// If the Json value is a number, return or cast it to a u64.
1025 /// Returns None otherwise.
1026 pub fn as_u64(&self) -> Option<u64> {
1028 Json::I64(n) => num::cast(n),
1029 Json::U64(n) => Some(n),
1034 /// If the Json value is a number, return or cast it to a f64.
1035 /// Returns None otherwise.
1036 pub fn as_f64(&self) -> Option<f64> {
1038 Json::I64(n) => num::cast(n),
1039 Json::U64(n) => num::cast(n),
1040 Json::F64(n) => Some(n),
1045 /// Returns true if the Json value is a Boolean. Returns false otherwise.
1046 pub fn is_boolean(&self) -> bool {
1047 self.as_boolean().is_some()
1050 /// If the Json value is a Boolean, returns the associated bool.
1051 /// Returns None otherwise.
1052 pub fn as_boolean(&self) -> Option<bool> {
1054 &Json::Boolean(b) => Some(b),
1059 /// Returns true if the Json value is a Null. Returns false otherwise.
1060 pub fn is_null(&self) -> bool {
1061 self.as_null().is_some()
1064 /// If the Json value is a Null, returns ().
1065 /// Returns None otherwise.
1066 pub fn as_null(&self) -> Option<()> {
1068 &Json::Null => Some(()),
1074 impl<'a> ops::Index<&'a str, Json> for Json {
1075 fn index<'a>(&'a self, idx: & &str) -> &'a Json {
1076 self.find(*idx).unwrap()
1080 impl ops::Index<uint, Json> for Json {
1081 fn index<'a>(&'a self, idx: &uint) -> &'a Json {
1083 &Json::Array(ref v) => v.index(idx),
1084 _ => panic!("can only index Json with uint if it is an array")
1089 /// The output of the streaming parser.
1090 #[deriving(PartialEq, Clone, Show)]
1091 pub enum JsonEvent {
1100 StringValue(string::String),
1105 #[deriving(PartialEq, Show)]
1107 // Parse a value in an array, true means first element.
1109 // Parse ',' or ']' after an element in an array.
1111 // Parse a key:value in an object, true means first element.
1113 // Parse ',' or ']' after an element in an object.
1117 // Expecting the stream to end.
1119 // Parsing can't continue.
1123 /// A Stack represents the current position of the parser in the logical
1124 /// structure of the JSON stream.
1125 /// For example foo.bar[3].x
1127 stack: Vec<InternalStackElement>,
1128 str_buffer: Vec<u8>,
1131 /// StackElements compose a Stack.
1132 /// For example, Key("foo"), Key("bar"), Index(3) and Key("x") are the
1133 /// StackElements compositing the stack that represents foo.bar[3].x
1134 #[deriving(PartialEq, Clone, Show)]
1135 pub enum StackElement<'l> {
1140 // Internally, Key elements are stored as indices in a buffer to avoid
1141 // allocating a string for every member of an object.
1142 #[deriving(PartialEq, Clone, Show)]
1143 enum InternalStackElement {
1145 InternalKey(u16, u16), // start, size
1149 pub fn new() -> Stack {
1150 Stack { stack: Vec::new(), str_buffer: Vec::new() }
1153 /// Returns The number of elements in the Stack.
1154 pub fn len(&self) -> uint { self.stack.len() }
1156 /// Returns true if the stack is empty.
1157 pub fn is_empty(&self) -> bool { self.stack.is_empty() }
1159 /// Provides access to the StackElement at a given index.
1160 /// lower indices are at the bottom of the stack while higher indices are
1162 pub fn get<'l>(&'l self, idx: uint) -> StackElement<'l> {
1163 match self.stack[idx] {
1164 InternalIndex(i) => Index(i),
1165 InternalKey(start, size) => {
1167 self.str_buffer[start as uint .. start as uint + size as uint]).unwrap())
1172 /// Compares this stack with an array of StackElements.
1173 pub fn is_equal_to(&self, rhs: &[StackElement]) -> bool {
1174 if self.stack.len() != rhs.len() { return false; }
1175 for i in range(0, rhs.len()) {
1176 if self.get(i) != rhs[i] { return false; }
1181 /// Returns true if the bottom-most elements of this stack are the same as
1182 /// the ones passed as parameter.
1183 pub fn starts_with(&self, rhs: &[StackElement]) -> bool {
1184 if self.stack.len() < rhs.len() { return false; }
1185 for i in range(0, rhs.len()) {
1186 if self.get(i) != rhs[i] { return false; }
1191 /// Returns true if the top-most elements of this stack are the same as
1192 /// the ones passed as parameter.
1193 pub fn ends_with(&self, rhs: &[StackElement]) -> bool {
1194 if self.stack.len() < rhs.len() { return false; }
1195 let offset = self.stack.len() - rhs.len();
1196 for i in range(0, rhs.len()) {
1197 if self.get(i + offset) != rhs[i] { return false; }
1202 /// Returns the top-most element (if any).
1203 pub fn top<'l>(&'l self) -> Option<StackElement<'l>> {
1204 return match self.stack.last() {
1206 Some(&InternalIndex(i)) => Some(Index(i)),
1207 Some(&InternalKey(start, size)) => {
1208 Some(Key(str::from_utf8(
1209 self.str_buffer[start as uint .. (start+size) as uint]
1215 // Used by Parser to insert Key elements at the top of the stack.
1216 fn push_key(&mut self, key: string::String) {
1217 self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
1218 for c in key.as_bytes().iter() {
1219 self.str_buffer.push(*c);
1223 // Used by Parser to insert Index elements at the top of the stack.
1224 fn push_index(&mut self, index: u32) {
1225 self.stack.push(InternalIndex(index));
1228 // Used by Parser to remove the top-most element of the stack.
1230 assert!(!self.is_empty());
1231 match *self.stack.last().unwrap() {
1232 InternalKey(_, sz) => {
1233 let new_size = self.str_buffer.len() - sz as uint;
1234 self.str_buffer.truncate(new_size);
1236 InternalIndex(_) => {}
1241 // Used by Parser to test whether the top-most element is an index.
1242 fn last_is_index(&self) -> bool {
1243 if self.is_empty() { return false; }
1244 return match *self.stack.last().unwrap() {
1245 InternalIndex(_) => true,
1250 // Used by Parser to increment the index of the top-most element.
1251 fn bump_index(&mut self) {
1252 let len = self.stack.len();
1253 let idx = match *self.stack.last().unwrap() {
1254 InternalIndex(i) => { i + 1 }
1257 self.stack[len - 1] = InternalIndex(idx);
1261 /// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
1262 /// an iterator of char.
1263 pub struct Parser<T> {
1268 // We maintain a stack representing where we are in the logical structure
1269 // of the JSON stream.
1271 // A state machine is kept to make it possible to interrupt and resume parsing.
1275 impl<T: Iterator<char>> Iterator<JsonEvent> for Parser<T> {
1276 fn next(&mut self) -> Option<JsonEvent> {
1277 if self.state == ParseFinished {
1281 if self.state == ParseBeforeFinish {
1282 self.parse_whitespace();
1283 // Make sure there is no trailing characters.
1285 self.state = ParseFinished;
1288 return Some(self.error_event(TrailingCharacters));
1292 return Some(self.parse());
1296 impl<T: Iterator<char>> Parser<T> {
1297 /// Creates the JSON parser.
1298 pub fn new(rdr: T) -> Parser<T> {
1299 let mut p = Parser {
1304 stack: Stack::new(),
1311 /// Provides access to the current position in the logical structure of the
1313 pub fn stack<'l>(&'l self) -> &'l Stack {
1317 fn eof(&self) -> bool { self.ch.is_none() }
1318 fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') }
1319 fn bump(&mut self) {
1320 self.ch = self.rdr.next();
1322 if self.ch_is('\n') {
1330 fn next_char(&mut self) -> Option<char> {
1334 fn ch_is(&self, c: char) -> bool {
1338 fn error<T>(&self, reason: ErrorCode) -> Result<T, ParserError> {
1339 Err(SyntaxError(reason, self.line, self.col))
1342 fn parse_whitespace(&mut self) {
1343 while self.ch_is(' ') ||
1346 self.ch_is('\r') { self.bump(); }
1349 fn parse_number(&mut self) -> JsonEvent {
1350 let mut neg = false;
1352 if self.ch_is('-') {
1357 let res = match self.parse_u64() {
1359 Err(e) => { return Error(e); }
1362 if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
1363 let mut res = res as f64;
1365 if self.ch_is('.') {
1366 res = match self.parse_decimal(res) {
1368 Err(e) => { return Error(e); }
1372 if self.ch_is('e') || self.ch_is('E') {
1373 res = match self.parse_exponent(res) {
1375 Err(e) => { return Error(e); }
1386 let res = -(res as i64);
1388 // Make sure we didn't underflow.
1390 Error(SyntaxError(InvalidNumber, self.line, self.col))
1400 fn parse_u64(&mut self) -> Result<u64, ParserError> {
1402 let last_accum = 0; // necessary to detect overflow.
1404 match self.ch_or_null() {
1408 // A leading '0' must be the only digit before the decimal point.
1409 match self.ch_or_null() {
1410 '0' ... '9' => return self.error(InvalidNumber),
1416 match self.ch_or_null() {
1417 c @ '0' ... '9' => {
1419 accum += (c as u64) - ('0' as u64);
1421 // Detect overflow by comparing to the last value.
1422 if accum <= last_accum { return self.error(InvalidNumber); }
1430 _ => return self.error(InvalidNumber),
1436 fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1439 // Make sure a digit follows the decimal place.
1440 match self.ch_or_null() {
1442 _ => return self.error(InvalidNumber)
1447 match self.ch_or_null() {
1448 c @ '0' ... '9' => {
1450 res += (((c as int) - ('0' as int)) as f64) * dec;
1460 fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1464 let mut neg_exp = false;
1466 if self.ch_is('+') {
1468 } else if self.ch_is('-') {
1473 // Make sure a digit follows the exponent place.
1474 match self.ch_or_null() {
1476 _ => return self.error(InvalidNumber)
1479 match self.ch_or_null() {
1480 c @ '0' ... '9' => {
1482 exp += (c as uint) - ('0' as uint);
1490 let exp = 10_f64.powi(exp as i32);
1500 fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1503 while i < 4 && !self.eof() {
1505 n = match self.ch_or_null() {
1506 c @ '0' ... '9' => n * 16 + ((c as u16) - ('0' as u16)),
1507 'a' | 'A' => n * 16 + 10,
1508 'b' | 'B' => n * 16 + 11,
1509 'c' | 'C' => n * 16 + 12,
1510 'd' | 'D' => n * 16 + 13,
1511 'e' | 'E' => n * 16 + 14,
1512 'f' | 'F' => n * 16 + 15,
1513 _ => return self.error(InvalidEscape)
1519 // Error out if we didn't parse 4 digits.
1521 return self.error(InvalidEscape);
1527 fn parse_str(&mut self) -> Result<string::String, ParserError> {
1528 let mut escape = false;
1529 let mut res = string::String::new();
1534 return self.error(EOFWhileParsingString);
1538 match self.ch_or_null() {
1539 '"' => res.push('"'),
1540 '\\' => res.push('\\'),
1541 '/' => res.push('/'),
1542 'b' => res.push('\x08'),
1543 'f' => res.push('\x0c'),
1544 'n' => res.push('\n'),
1545 'r' => res.push('\r'),
1546 't' => res.push('\t'),
1547 'u' => match try!(self.decode_hex_escape()) {
1548 0xDC00 ... 0xDFFF => {
1549 return self.error(LoneLeadingSurrogateInHexEscape)
1552 // Non-BMP characters are encoded as a sequence of
1553 // two hex escapes, representing UTF-16 surrogates.
1554 n1 @ 0xD800 ... 0xDBFF => {
1555 match (self.next_char(), self.next_char()) {
1556 (Some('\\'), Some('u')) => (),
1557 _ => return self.error(UnexpectedEndOfHexEscape),
1560 let buf = [n1, try!(self.decode_hex_escape())];
1561 match str::utf16_items(buf.as_slice()).next() {
1562 Some(ScalarValue(c)) => res.push(c),
1563 _ => return self.error(LoneLeadingSurrogateInHexEscape),
1567 n => match char::from_u32(n as u32) {
1568 Some(c) => res.push(c),
1569 None => return self.error(InvalidUnicodeCodePoint),
1572 _ => return self.error(InvalidEscape),
1575 } else if self.ch_is('\\') {
1583 Some(c) => res.push(c),
1584 None => unreachable!()
1590 // Invoked at each iteration, consumes the stream until it has enough
1591 // information to return a JsonEvent.
1592 // Manages an internal state so that parsing can be interrupted and resumed.
1593 // Also keeps track of the position in the logical structure of the json
1594 // stream int the form of a stack that can be queried by the user using the
1596 fn parse(&mut self) -> JsonEvent {
1598 // The only paths where the loop can spin a new iteration
1599 // are in the cases ParseArrayComma and ParseObjectComma if ','
1600 // is parsed. In these cases the state is set to (respectively)
1601 // ParseArray(false) and ParseObject(false), which always return,
1602 // so there is no risk of getting stuck in an infinite loop.
1603 // All other paths return before the end of the loop's iteration.
1604 self.parse_whitespace();
1608 return self.parse_start();
1610 ParseArray(first) => {
1611 return self.parse_array(first);
1613 ParseArrayComma => {
1614 match self.parse_array_comma_or_end() {
1615 Some(evt) => { return evt; }
1619 ParseObject(first) => {
1620 return self.parse_object(first);
1622 ParseObjectComma => {
1624 if self.ch_is(',') {
1625 self.state = ParseObject(false);
1628 return self.parse_object_end();
1632 return self.error_event(InvalidSyntax);
1638 fn parse_start(&mut self) -> JsonEvent {
1639 let val = self.parse_value();
1640 self.state = match val {
1641 Error(_) => ParseFinished,
1642 ArrayStart => ParseArray(true),
1643 ObjectStart => ParseObject(true),
1644 _ => ParseBeforeFinish,
1649 fn parse_array(&mut self, first: bool) -> JsonEvent {
1650 if self.ch_is(']') {
1652 self.error_event(InvalidSyntax)
1654 self.state = if self.stack.is_empty() {
1656 } else if self.stack.last_is_index() {
1666 self.stack.push_index(0);
1668 let val = self.parse_value();
1669 self.state = match val {
1670 Error(_) => ParseFinished,
1671 ArrayStart => ParseArray(true),
1672 ObjectStart => ParseObject(true),
1673 _ => ParseArrayComma,
1679 fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
1680 if self.ch_is(',') {
1681 self.stack.bump_index();
1682 self.state = ParseArray(false);
1685 } else if self.ch_is(']') {
1687 self.state = if self.stack.is_empty() {
1689 } else if self.stack.last_is_index() {
1696 } else if self.eof() {
1697 Some(self.error_event(EOFWhileParsingArray))
1699 Some(self.error_event(InvalidSyntax))
1703 fn parse_object(&mut self, first: bool) -> JsonEvent {
1704 if self.ch_is('}') {
1706 if self.stack.is_empty() {
1707 return self.error_event(TrailingComma);
1712 self.state = if self.stack.is_empty() {
1714 } else if self.stack.last_is_index() {
1723 return self.error_event(EOFWhileParsingObject);
1725 if !self.ch_is('"') {
1726 return self.error_event(KeyMustBeAString);
1728 let s = match self.parse_str() {
1731 self.state = ParseFinished;
1735 self.parse_whitespace();
1737 return self.error_event(EOFWhileParsingObject);
1738 } else if self.ch_or_null() != ':' {
1739 return self.error_event(ExpectedColon);
1741 self.stack.push_key(s);
1743 self.parse_whitespace();
1745 let val = self.parse_value();
1747 self.state = match val {
1748 Error(_) => ParseFinished,
1749 ArrayStart => ParseArray(true),
1750 ObjectStart => ParseObject(true),
1751 _ => ParseObjectComma,
1756 fn parse_object_end(&mut self) -> JsonEvent {
1757 if self.ch_is('}') {
1758 self.state = if self.stack.is_empty() {
1760 } else if self.stack.last_is_index() {
1767 } else if self.eof() {
1768 self.error_event(EOFWhileParsingObject)
1770 self.error_event(InvalidSyntax)
1774 fn parse_value(&mut self) -> JsonEvent {
1775 if self.eof() { return self.error_event(EOFWhileParsingValue); }
1776 match self.ch_or_null() {
1777 'n' => { self.parse_ident("ull", NullValue) }
1778 't' => { self.parse_ident("rue", BooleanValue(true)) }
1779 'f' => { self.parse_ident("alse", BooleanValue(false)) }
1780 '0' ... '9' | '-' => self.parse_number(),
1781 '"' => match self.parse_str() {
1782 Ok(s) => StringValue(s),
1793 _ => { self.error_event(InvalidSyntax) }
1797 fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
1798 if ident.chars().all(|c| Some(c) == self.next_char()) {
1802 Error(SyntaxError(InvalidSyntax, self.line, self.col))
1806 fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
1807 self.state = ParseFinished;
1808 Error(SyntaxError(reason, self.line, self.col))
1812 /// A Builder consumes a json::Parser to create a generic Json structure.
1813 pub struct Builder<T> {
1815 token: Option<JsonEvent>,
1818 impl<T: Iterator<char>> Builder<T> {
1819 /// Create a JSON Builder.
1820 pub fn new(src: T) -> Builder<T> {
1821 Builder { parser: Parser::new(src), token: None, }
1824 // Decode a Json value from a Parser.
1825 pub fn build(&mut self) -> Result<Json, BuilderError> {
1827 let result = self.build_value();
1831 Some(Error(e)) => { return Err(e); }
1832 ref tok => { panic!("unexpected token {}", tok.clone()); }
1837 fn bump(&mut self) {
1838 self.token = self.parser.next();
1841 fn build_value(&mut self) -> Result<Json, BuilderError> {
1842 return match self.token {
1843 Some(NullValue) => Ok(Json::Null),
1844 Some(I64Value(n)) => Ok(Json::I64(n)),
1845 Some(U64Value(n)) => Ok(Json::U64(n)),
1846 Some(F64Value(n)) => Ok(Json::F64(n)),
1847 Some(BooleanValue(b)) => Ok(Json::Boolean(b)),
1848 Some(StringValue(ref mut s)) => {
1849 let mut temp = string::String::new();
1851 Ok(Json::String(temp))
1853 Some(Error(e)) => Err(e),
1854 Some(ArrayStart) => self.build_array(),
1855 Some(ObjectStart) => self.build_object(),
1856 Some(ObjectEnd) => self.parser.error(InvalidSyntax),
1857 Some(ArrayEnd) => self.parser.error(InvalidSyntax),
1858 None => self.parser.error(EOFWhileParsingValue),
1862 fn build_array(&mut self) -> Result<Json, BuilderError> {
1864 let mut values = Vec::new();
1867 if self.token == Some(ArrayEnd) {
1868 return Ok(Json::Array(values.into_iter().collect()));
1870 match self.build_value() {
1871 Ok(v) => values.push(v),
1872 Err(e) => { return Err(e) }
1878 fn build_object(&mut self) -> Result<Json, BuilderError> {
1881 let mut values = TreeMap::new();
1885 Some(ObjectEnd) => { return Ok(Json::Object(values)); }
1886 Some(Error(e)) => { return Err(e); }
1890 let key = match self.parser.stack().top() {
1891 Some(Key(k)) => { k.to_string() }
1892 _ => { panic!("invalid state"); }
1894 match self.build_value() {
1895 Ok(value) => { values.insert(key, value); }
1896 Err(e) => { return Err(e); }
1900 return self.parser.error(EOFWhileParsingObject);
1904 /// Decodes a json value from an `&mut io::Reader`
1905 pub fn from_reader(rdr: &mut io::Reader) -> Result<Json, BuilderError> {
1906 let contents = match rdr.read_to_end() {
1908 Err(e) => return Err(io_error_to_error(e))
1910 let s = match str::from_utf8(contents.as_slice()) {
1912 _ => return Err(SyntaxError(NotUtf8, 0, 0))
1914 let mut builder = Builder::new(s.chars());
1918 /// Decodes a json value from a string
1919 pub fn from_str(s: &str) -> Result<Json, BuilderError> {
1920 let mut builder = Builder::new(s.chars());
1924 /// A structure to decode JSON to values in rust.
1925 pub struct Decoder {
1930 /// Creates a new decoder instance for decoding the specified JSON value.
1931 pub fn new(json: Json) -> Decoder {
1932 Decoder { stack: vec![json] }
1937 fn pop(&mut self) -> Json {
1938 self.stack.pop().unwrap()
1942 macro_rules! expect(
1943 ($e:expr, Null) => ({
1945 Json::Null => Ok(()),
1946 other => Err(ExpectedError("Null".to_string(),
1947 format!("{}", other)))
1950 ($e:expr, $t:ident) => ({
1952 Json::$t(v) => Ok(v),
1954 Err(ExpectedError(stringify!($t).to_string(),
1955 format!("{}", other)))
1961 macro_rules! read_primitive {
1962 ($name:ident, $ty:ty) => {
1963 fn $name(&mut self) -> DecodeResult<$ty> {
1966 match num::cast(f) {
1968 None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
1972 match num::cast(f) {
1974 None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
1978 Err(ExpectedError("Integer".to_string(), format!("{}", f)))
1980 Json::String(s) => {
1981 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
1982 // is going to have a string here, as per JSON spec.
1983 match std::str::from_str(s.as_slice()) {
1985 None => Err(ExpectedError("Number".to_string(), s)),
1988 value => Err(ExpectedError("Number".to_string(), format!("{}", value)))
1994 impl ::Decoder<DecoderError> for Decoder {
1995 fn read_nil(&mut self) -> DecodeResult<()> {
1997 expect!(self.pop(), Null)
2000 read_primitive!(read_uint, uint)
2001 read_primitive!(read_u8, u8)
2002 read_primitive!(read_u16, u16)
2003 read_primitive!(read_u32, u32)
2004 read_primitive!(read_u64, u64)
2005 read_primitive!(read_int, int)
2006 read_primitive!(read_i8, i8)
2007 read_primitive!(read_i16, i16)
2008 read_primitive!(read_i32, i32)
2009 read_primitive!(read_i64, i64)
2011 fn read_f32(&mut self) -> DecodeResult<f32> { self.read_f64().map(|x| x as f32) }
2013 fn read_f64(&mut self) -> DecodeResult<f64> {
2016 Json::I64(f) => Ok(f as f64),
2017 Json::U64(f) => Ok(f as f64),
2018 Json::F64(f) => Ok(f),
2019 Json::String(s) => {
2020 // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
2021 // is going to have a string here, as per JSON spec.
2022 match std::str::from_str(s.as_slice()) {
2024 None => Err(ExpectedError("Number".to_string(), s)),
2027 Json::Null => Ok(f64::NAN),
2028 value => Err(ExpectedError("Number".to_string(), format!("{}", value)))
2032 fn read_bool(&mut self) -> DecodeResult<bool> {
2033 debug!("read_bool");
2034 expect!(self.pop(), Boolean)
2037 fn read_char(&mut self) -> DecodeResult<char> {
2038 let s = try!(self.read_str());
2040 let mut it = s.chars();
2041 match (it.next(), it.next()) {
2042 // exactly one character
2043 (Some(c), None) => return Ok(c),
2047 Err(ExpectedError("single character string".to_string(), format!("{}", s)))
2050 fn read_str(&mut self) -> DecodeResult<string::String> {
2052 expect!(self.pop(), String)
2055 fn read_enum<T>(&mut self,
2057 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
2058 debug!("read_enum({})", name);
2062 fn read_enum_variant<T>(&mut self,
2064 f: |&mut Decoder, uint| -> DecodeResult<T>)
2065 -> DecodeResult<T> {
2066 debug!("read_enum_variant(names={})", names);
2067 let name = match self.pop() {
2068 Json::String(s) => s,
2069 Json::Object(mut o) => {
2070 let n = match o.remove(&"variant".to_string()) {
2071 Some(Json::String(s)) => s,
2073 return Err(ExpectedError("String".to_string(), format!("{}", val)))
2076 return Err(MissingFieldError("variant".to_string()))
2079 match o.remove(&"fields".to_string()) {
2080 Some(Json::Array(l)) => {
2081 for field in l.into_iter().rev() {
2082 self.stack.push(field);
2086 return Err(ExpectedError("Array".to_string(), format!("{}", val)))
2089 return Err(MissingFieldError("fields".to_string()))
2095 return Err(ExpectedError("String or Object".to_string(), format!("{}", json)))
2098 let idx = match names.iter()
2099 .position(|n| str::eq_slice(*n, name.as_slice())) {
2101 None => return Err(UnknownVariantError(name))
2106 fn read_enum_variant_arg<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
2107 -> DecodeResult<T> {
2108 debug!("read_enum_variant_arg(idx={})", idx);
2112 fn read_enum_struct_variant<T>(&mut self,
2114 f: |&mut Decoder, uint| -> DecodeResult<T>)
2115 -> DecodeResult<T> {
2116 debug!("read_enum_struct_variant(names={})", names);
2117 self.read_enum_variant(names, f)
2121 fn read_enum_struct_variant_field<T>(&mut self,
2124 f: |&mut Decoder| -> DecodeResult<T>)
2125 -> DecodeResult<T> {
2126 debug!("read_enum_struct_variant_field(name={}, idx={})", name, idx);
2127 self.read_enum_variant_arg(idx, f)
2130 fn read_struct<T>(&mut self,
2133 f: |&mut Decoder| -> DecodeResult<T>)
2134 -> DecodeResult<T> {
2135 debug!("read_struct(name={}, len={})", name, len);
2136 let value = try!(f(self));
2141 fn read_struct_field<T>(&mut self,
2144 f: |&mut Decoder| -> DecodeResult<T>)
2145 -> DecodeResult<T> {
2146 debug!("read_struct_field(name={}, idx={})", name, idx);
2147 let mut obj = try!(expect!(self.pop(), Object));
2149 let value = match obj.remove(&name.to_string()) {
2151 // Add a Null and try to parse it as an Option<_>
2152 // to get None as a default value.
2153 self.stack.push(Json::Null);
2156 Err(_) => return Err(MissingFieldError(name.to_string())),
2160 self.stack.push(json);
2164 self.stack.push(Json::Object(obj));
2168 fn read_tuple<T>(&mut self,
2170 f: |&mut Decoder| -> DecodeResult<T>)
2171 -> DecodeResult<T> {
2172 debug!("read_tuple()");
2173 self.read_seq(|d, len| {
2174 if len == tuple_len {
2177 Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)))
2182 fn read_tuple_arg<T>(&mut self,
2184 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
2185 debug!("read_tuple_arg(idx={})", idx);
2186 self.read_seq_elt(idx, f)
2189 fn read_tuple_struct<T>(&mut self,
2192 f: |&mut Decoder| -> DecodeResult<T>)
2193 -> DecodeResult<T> {
2194 debug!("read_tuple_struct(name={})", name);
2195 self.read_tuple(len, f)
2198 fn read_tuple_struct_arg<T>(&mut self,
2200 f: |&mut Decoder| -> DecodeResult<T>)
2201 -> DecodeResult<T> {
2202 debug!("read_tuple_struct_arg(idx={})", idx);
2203 self.read_tuple_arg(idx, f)
2206 fn read_option<T>(&mut self, f: |&mut Decoder, bool| -> DecodeResult<T>) -> DecodeResult<T> {
2207 debug!("read_option()");
2209 Json::Null => f(self, false),
2210 value => { self.stack.push(value); f(self, true) }
2214 fn read_seq<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
2215 debug!("read_seq()");
2216 let array = try!(expect!(self.pop(), Array));
2217 let len = array.len();
2218 for v in array.into_iter().rev() {
2224 fn read_seq_elt<T>(&mut self,
2226 f: |&mut Decoder| -> DecodeResult<T>) -> DecodeResult<T> {
2227 debug!("read_seq_elt(idx={})", idx);
2231 fn read_map<T>(&mut self, f: |&mut Decoder, uint| -> DecodeResult<T>) -> DecodeResult<T> {
2232 debug!("read_map()");
2233 let obj = try!(expect!(self.pop(), Object));
2234 let len = obj.len();
2235 for (key, value) in obj.into_iter() {
2236 self.stack.push(value);
2237 self.stack.push(Json::String(key));
2242 fn read_map_elt_key<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
2243 -> DecodeResult<T> {
2244 debug!("read_map_elt_key(idx={})", idx);
2248 fn read_map_elt_val<T>(&mut self, idx: uint, f: |&mut Decoder| -> DecodeResult<T>)
2249 -> DecodeResult<T> {
2250 debug!("read_map_elt_val(idx={})", idx);
2254 fn error(&mut self, err: &str) -> DecoderError {
2255 ApplicationError(err.to_string())
2259 /// A trait for converting values to JSON
2260 pub trait ToJson for Sized? {
2261 /// Converts the value of `self` to an instance of JSON
2262 fn to_json(&self) -> Json;
2265 macro_rules! to_json_impl_i64(
2267 $(impl ToJson for $t {
2268 fn to_json(&self) -> Json { Json::I64(*self as i64) }
2273 to_json_impl_i64!(int, i8, i16, i32, i64)
2275 macro_rules! to_json_impl_u64(
2277 $(impl ToJson for $t {
2278 fn to_json(&self) -> Json { Json::U64(*self as u64) }
2283 to_json_impl_u64!(uint, u8, u16, u32, u64)
2285 impl ToJson for Json {
2286 fn to_json(&self) -> Json { self.clone() }
2289 impl ToJson for f32 {
2290 fn to_json(&self) -> Json { (*self as f64).to_json() }
2293 impl ToJson for f64 {
2294 fn to_json(&self) -> Json {
2295 match self.classify() {
2296 FPNaN | FPInfinite => Json::Null,
2297 _ => Json::F64(*self)
2302 impl ToJson for () {
2303 fn to_json(&self) -> Json { Json::Null }
2306 impl ToJson for bool {
2307 fn to_json(&self) -> Json { Json::Boolean(*self) }
2310 impl ToJson for str {
2311 fn to_json(&self) -> Json { Json::String(self.into_string()) }
2314 impl ToJson for string::String {
2315 fn to_json(&self) -> Json { Json::String((*self).clone()) }
2318 macro_rules! tuple_impl {
2319 // use variables to indicate the arity of the tuple
2320 ($($tyvar:ident),* ) => {
2321 // the trailing commas are for the 1 tuple
2323 $( $tyvar : ToJson ),*
2324 > ToJson for ( $( $tyvar ),* , ) {
2327 #[allow(non_snake_case)]
2328 fn to_json(&self) -> Json {
2330 ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
2339 tuple_impl!{A, B, C}
2340 tuple_impl!{A, B, C, D}
2341 tuple_impl!{A, B, C, D, E}
2342 tuple_impl!{A, B, C, D, E, F}
2343 tuple_impl!{A, B, C, D, E, F, G}
2344 tuple_impl!{A, B, C, D, E, F, G, H}
2345 tuple_impl!{A, B, C, D, E, F, G, H, I}
2346 tuple_impl!{A, B, C, D, E, F, G, H, I, J}
2347 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K}
2348 tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L}
2350 impl<A: ToJson> ToJson for [A] {
2351 fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2354 impl<A: ToJson> ToJson for Vec<A> {
2355 fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) }
2358 impl<A: ToJson> ToJson for TreeMap<string::String, A> {
2359 fn to_json(&self) -> Json {
2360 let mut d = TreeMap::new();
2361 for (key, value) in self.iter() {
2362 d.insert((*key).clone(), value.to_json());
2368 impl<A: ToJson> ToJson for HashMap<string::String, A> {
2369 fn to_json(&self) -> Json {
2370 let mut d = TreeMap::new();
2371 for (key, value) in self.iter() {
2372 d.insert((*key).clone(), value.to_json());
2378 impl<A:ToJson> ToJson for Option<A> {
2379 fn to_json(&self) -> Json {
2382 Some(ref value) => value.to_json()
2387 impl fmt::Show for Json {
2388 /// Encodes a json value into a string
2389 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2390 self.to_writer(f).map_err(|_| fmt::Error)
2394 impl FromStr for Json {
2395 fn from_str(s: &str) -> Option<Json> {
2403 use self::Animal::*;
2404 use self::DecodeEnum::*;
2405 use self::test::Bencher;
2406 use {Encodable, Decodable};
2408 use super::ErrorCode::*;
2409 use super::ParserError::*;
2410 use super::DecoderError::*;
2411 use super::JsonEvent::*;
2412 use super::ParserState::*;
2413 use super::StackElement::*;
2414 use super::InternalStackElement::*;
2415 use super::{PrettyEncoder, Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser,
2416 StackElement, Stack, Encoder, Decoder};
2417 use std::{i64, u64, f32, f64, io};
2418 use std::collections::TreeMap;
2419 use std::num::Float;
2422 #[deriving(Decodable, Eq, PartialEq, Show)]
2428 fn test_decode_option_none() {
2430 let obj: OptionData = super::decode(s).unwrap();
2431 assert_eq!(obj, OptionData { opt: None });
2435 fn test_decode_option_some() {
2436 let s = "{ \"opt\": 10 }";
2437 let obj: OptionData = super::decode(s).unwrap();
2438 assert_eq!(obj, OptionData { opt: Some(10u) });
2442 fn test_decode_option_malformed() {
2443 check_err::<OptionData>("{ \"opt\": [] }",
2444 ExpectedError("Number".to_string(), "[]".to_string()));
2445 check_err::<OptionData>("{ \"opt\": false }",
2446 ExpectedError("Number".to_string(), "false".to_string()));
2449 #[deriving(PartialEq, Encodable, Decodable, Show)]
2452 Frog(string::String, int)
2455 #[deriving(PartialEq, Encodable, Decodable, Show)]
2459 c: Vec<string::String>,
2462 #[deriving(PartialEq, Encodable, Decodable, Show)]
2467 fn mk_object(items: &[(string::String, Json)]) -> Json {
2468 let mut d = TreeMap::new();
2470 for item in items.iter() {
2472 (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
2480 fn test_from_str_trait() {
2482 assert!(::std::str::from_str::<Json>(s).unwrap() == from_str(s).unwrap());
2486 fn test_write_null() {
2487 assert_eq!(Null.to_string().into_string(), "null");
2488 assert_eq!(Null.to_pretty_str().into_string(), "null");
2492 fn test_write_i64() {
2493 assert_eq!(U64(0).to_string().into_string(), "0");
2494 assert_eq!(U64(0).to_pretty_str().into_string(), "0");
2496 assert_eq!(U64(1234).to_string().into_string(), "1234");
2497 assert_eq!(U64(1234).to_pretty_str().into_string(), "1234");
2499 assert_eq!(I64(-5678).to_string().into_string(), "-5678");
2500 assert_eq!(I64(-5678).to_pretty_str().into_string(), "-5678");
2502 assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000");
2503 assert_eq!(U64(7650007200025252000).to_pretty_str(), "7650007200025252000");
2507 fn test_write_f64() {
2508 assert_eq!(F64(3.0).to_string().into_string(), "3.0");
2509 assert_eq!(F64(3.0).to_pretty_str().into_string(), "3.0");
2511 assert_eq!(F64(3.1).to_string().into_string(), "3.1");
2512 assert_eq!(F64(3.1).to_pretty_str().into_string(), "3.1");
2514 assert_eq!(F64(-1.5).to_string().into_string(), "-1.5");
2515 assert_eq!(F64(-1.5).to_pretty_str().into_string(), "-1.5");
2517 assert_eq!(F64(0.5).to_string().into_string(), "0.5");
2518 assert_eq!(F64(0.5).to_pretty_str().into_string(), "0.5");
2520 assert_eq!(F64(f64::NAN).to_string().into_string(), "null");
2521 assert_eq!(F64(f64::NAN).to_pretty_str().into_string(), "null");
2523 assert_eq!(F64(f64::INFINITY).to_string().into_string(), "null");
2524 assert_eq!(F64(f64::INFINITY).to_pretty_str().into_string(), "null");
2526 assert_eq!(F64(f64::NEG_INFINITY).to_string().into_string(), "null");
2527 assert_eq!(F64(f64::NEG_INFINITY).to_pretty_str().into_string(), "null");
2531 fn test_write_str() {
2532 assert_eq!(String("".to_string()).to_string().into_string(), "\"\"");
2533 assert_eq!(String("".to_string()).to_pretty_str().into_string(), "\"\"");
2535 assert_eq!(String("foo".to_string()).to_string().into_string(), "\"foo\"");
2536 assert_eq!(String("foo".to_string()).to_pretty_str().into_string(), "\"foo\"");
2540 fn test_write_bool() {
2541 assert_eq!(Boolean(true).to_string().into_string(), "true");
2542 assert_eq!(Boolean(true).to_pretty_str().into_string(), "true");
2544 assert_eq!(Boolean(false).to_string().into_string(), "false");
2545 assert_eq!(Boolean(false).to_pretty_str().into_string(), "false");
2549 fn test_write_array() {
2550 assert_eq!(Array(vec![]).to_string().into_string(), "[]");
2551 assert_eq!(Array(vec![]).to_pretty_str().into_string(), "[]");
2553 assert_eq!(Array(vec![Boolean(true)]).to_string().into_string(), "[true]");
2555 Array(vec![Boolean(true)]).to_pretty_str().into_string(),
2562 let long_test_array = Array(vec![
2565 Array(vec![String("foo\nbar".to_string()), F64(3.5)])]);
2567 assert_eq!(long_test_array.to_string().into_string(),
2568 "[false,null,[\"foo\\nbar\",3.5]]");
2570 long_test_array.to_pretty_str().into_string(),
2584 fn test_write_object() {
2585 assert_eq!(mk_object(&[]).to_string().into_string(), "{}");
2586 assert_eq!(mk_object(&[]).to_pretty_str().into_string(), "{}");
2590 ("a".to_string(), Boolean(true))
2591 ]).to_string().into_string(),
2595 mk_object(&[("a".to_string(), Boolean(true))]).to_pretty_str(),
2602 let complex_obj = mk_object(&[
2603 ("b".to_string(), Array(vec![
2604 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2605 mk_object(&[("d".to_string(), String("".to_string()))])
2610 complex_obj.to_string().into_string(),
2613 {\"c\":\"\\f\\r\"},\
2619 complex_obj.to_pretty_str().into_string(),
2624 \"c\": \"\\f\\r\"\n \
2633 let a = mk_object(&[
2634 ("a".to_string(), Boolean(true)),
2635 ("b".to_string(), Array(vec![
2636 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
2637 mk_object(&[("d".to_string(), String("".to_string()))])
2641 // We can't compare the strings directly because the object fields be
2642 // printed in a different order.
2643 assert_eq!(a.clone(), from_str(a.to_string().as_slice()).unwrap());
2644 assert_eq!(a.clone(),
2645 from_str(a.to_pretty_str().as_slice()).unwrap());
2648 fn with_str_writer(f: |&mut io::Writer|) -> string::String {
2651 let mut m = Vec::new();
2652 f(&mut m as &mut io::Writer);
2653 string::String::from_utf8(m).unwrap()
2657 fn test_write_enum() {
2660 with_str_writer(|writer| {
2661 let mut encoder = Encoder::new(writer);
2662 animal.encode(&mut encoder).unwrap();
2667 with_str_writer(|writer| {
2668 let mut encoder = PrettyEncoder::new(writer);
2669 animal.encode(&mut encoder).unwrap();
2674 let animal = Frog("Henry".to_string(), 349);
2676 with_str_writer(|writer| {
2677 let mut encoder = Encoder::new(writer);
2678 animal.encode(&mut encoder).unwrap();
2680 "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
2683 with_str_writer(|writer| {
2684 let mut encoder = PrettyEncoder::new(writer);
2685 animal.encode(&mut encoder).unwrap();
2688 \"variant\": \"Frog\",\n \
2698 fn test_write_some() {
2699 let value = Some("jodhpurs".to_string());
2700 let s = with_str_writer(|writer| {
2701 let mut encoder = Encoder::new(writer);
2702 value.encode(&mut encoder).unwrap();
2704 assert_eq!(s, "\"jodhpurs\"");
2706 let value = Some("jodhpurs".to_string());
2707 let s = with_str_writer(|writer| {
2708 let mut encoder = PrettyEncoder::new(writer);
2709 value.encode(&mut encoder).unwrap();
2711 assert_eq!(s, "\"jodhpurs\"");
2715 fn test_write_none() {
2716 let value: Option<string::String> = None;
2717 let s = with_str_writer(|writer| {
2718 let mut encoder = Encoder::new(writer);
2719 value.encode(&mut encoder).unwrap();
2721 assert_eq!(s, "null");
2723 let s = with_str_writer(|writer| {
2724 let mut encoder = Encoder::new(writer);
2725 value.encode(&mut encoder).unwrap();
2727 assert_eq!(s, "null");
2731 fn test_trailing_characters() {
2732 assert_eq!(from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2733 assert_eq!(from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5)));
2734 assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
2735 assert_eq!(from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2)));
2736 assert_eq!(from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2737 assert_eq!(from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
2741 fn test_read_identifiers() {
2742 assert_eq!(from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2743 assert_eq!(from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2744 assert_eq!(from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2745 assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2746 assert_eq!(from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2)));
2747 assert_eq!(from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3)));
2749 assert_eq!(from_str("null"), Ok(Null));
2750 assert_eq!(from_str("true"), Ok(Boolean(true)));
2751 assert_eq!(from_str("false"), Ok(Boolean(false)));
2752 assert_eq!(from_str(" null "), Ok(Null));
2753 assert_eq!(from_str(" true "), Ok(Boolean(true)));
2754 assert_eq!(from_str(" false "), Ok(Boolean(false)));
2758 fn test_decode_identifiers() {
2759 let v: () = super::decode("null").unwrap();
2762 let v: bool = super::decode("true").unwrap();
2763 assert_eq!(v, true);
2765 let v: bool = super::decode("false").unwrap();
2766 assert_eq!(v, false);
2770 fn test_read_number() {
2771 assert_eq!(from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2772 assert_eq!(from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1)));
2773 assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
2774 assert_eq!(from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2)));
2775 assert_eq!(from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2)));
2776 assert_eq!(from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3)));
2777 assert_eq!(from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3)));
2778 assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
2780 assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20)));
2781 assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21)));
2783 assert_eq!(from_str("3"), Ok(U64(3)));
2784 assert_eq!(from_str("3.1"), Ok(F64(3.1)));
2785 assert_eq!(from_str("-1.2"), Ok(F64(-1.2)));
2786 assert_eq!(from_str("0.4"), Ok(F64(0.4)));
2787 assert_eq!(from_str("0.4e5"), Ok(F64(0.4e5)));
2788 assert_eq!(from_str("0.4e+15"), Ok(F64(0.4e15)));
2789 assert_eq!(from_str("0.4e-01"), Ok(F64(0.4e-01)));
2790 assert_eq!(from_str(" 3 "), Ok(U64(3)));
2792 assert_eq!(from_str("-9223372036854775808"), Ok(I64(i64::MIN)));
2793 assert_eq!(from_str("9223372036854775807"), Ok(U64(i64::MAX as u64)));
2794 assert_eq!(from_str("18446744073709551615"), Ok(U64(u64::MAX)));
2798 fn test_decode_numbers() {
2799 let v: f64 = super::decode("3").unwrap();
2802 let v: f64 = super::decode("3.1").unwrap();
2805 let v: f64 = super::decode("-1.2").unwrap();
2806 assert_eq!(v, -1.2);
2808 let v: f64 = super::decode("0.4").unwrap();
2811 let v: f64 = super::decode("0.4e5").unwrap();
2812 assert_eq!(v, 0.4e5);
2814 let v: f64 = super::decode("0.4e15").unwrap();
2815 assert_eq!(v, 0.4e15);
2817 let v: f64 = super::decode("0.4e-01").unwrap();
2818 assert_eq!(v, 0.4e-01);
2820 let v: u64 = super::decode("0").unwrap();
2823 let v: u64 = super::decode("18446744073709551615").unwrap();
2824 assert_eq!(v, u64::MAX);
2826 let v: i64 = super::decode("-9223372036854775808").unwrap();
2827 assert_eq!(v, i64::MIN);
2829 let v: i64 = super::decode("9223372036854775807").unwrap();
2830 assert_eq!(v, i64::MAX);
2832 let res: DecodeResult<i64> = super::decode("765.25252");
2833 assert_eq!(res, Err(ExpectedError("Integer".into_string(), "765.25252".into_string())));
2837 fn test_read_str() {
2838 assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2)));
2839 assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
2841 assert_eq!(from_str("\"\""), Ok(String("".to_string())));
2842 assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
2843 assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
2844 assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
2845 assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
2846 assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
2847 assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
2848 assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
2849 assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u12ab".to_string())));
2850 assert_eq!(from_str("\"\\uAB12\""), Ok(String("\uAB12".to_string())));
2854 fn test_decode_str() {
2855 let s = [("\"\"", ""),
2858 ("\"\\b\"", "\x08"),
2862 ("\"\\u12ab\"", "\u12ab"),
2863 ("\"\\uAB12\"", "\uAB12")];
2865 for &(i, o) in s.iter() {
2866 let v: string::String = super::decode(i).unwrap();
2872 fn test_read_array() {
2873 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
2874 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
2875 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
2876 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2877 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
2879 assert_eq!(from_str("[]"), Ok(Array(vec![])));
2880 assert_eq!(from_str("[ ]"), Ok(Array(vec![])));
2881 assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)])));
2882 assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)])));
2883 assert_eq!(from_str("[null]"), Ok(Array(vec![Null])));
2884 assert_eq!(from_str("[3, 1]"),
2885 Ok(Array(vec![U64(3), U64(1)])));
2886 assert_eq!(from_str("\n[3, 2]\n"),
2887 Ok(Array(vec![U64(3), U64(2)])));
2888 assert_eq!(from_str("[2, [4, 1]]"),
2889 Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])])));
2893 fn test_decode_array() {
2894 let v: Vec<()> = super::decode("[]").unwrap();
2895 assert_eq!(v, vec![]);
2897 let v: Vec<()> = super::decode("[null]").unwrap();
2898 assert_eq!(v, vec![()]);
2900 let v: Vec<bool> = super::decode("[true]").unwrap();
2901 assert_eq!(v, vec![true]);
2903 let v: Vec<int> = super::decode("[3, 1]").unwrap();
2904 assert_eq!(v, vec![3, 1]);
2906 let v: Vec<Vec<uint>> = super::decode("[[3], [1, 2]]").unwrap();
2907 assert_eq!(v, vec![vec![3], vec![1, 2]]);
2911 fn test_decode_tuple() {
2912 let t: (uint, uint, uint) = super::decode("[1, 2, 3]").unwrap();
2913 assert_eq!(t, (1u, 2, 3))
2915 let t: (uint, string::String) = super::decode("[1, \"two\"]").unwrap();
2916 assert_eq!(t, (1u, "two".to_string()));
2920 fn test_decode_tuple_malformed_types() {
2921 assert!(super::decode::<(uint, string::String)>("[1, 2]").is_err());
2925 fn test_decode_tuple_malformed_length() {
2926 assert!(super::decode::<(uint, uint)>("[1, 2, 3]").is_err());
2930 fn test_read_object() {
2931 assert_eq!(from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
2932 assert_eq!(from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
2933 assert_eq!(from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2)));
2934 assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
2935 assert_eq!(from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
2936 assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
2938 assert_eq!(from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6)));
2939 assert_eq!(from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6)));
2940 assert_eq!(from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
2941 assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8)));
2942 assert_eq!(from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
2944 assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
2945 assert_eq!(from_str("{\"a\": 3}").unwrap(),
2946 mk_object(&[("a".to_string(), U64(3))]));
2948 assert_eq!(from_str(
2949 "{ \"a\": null, \"b\" : true }").unwrap(),
2951 ("a".to_string(), Null),
2952 ("b".to_string(), Boolean(true))]));
2953 assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
2955 ("a".to_string(), Null),
2956 ("b".to_string(), Boolean(true))]));
2957 assert_eq!(from_str(
2958 "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
2960 ("a".to_string(), F64(1.0)),
2961 ("b".to_string(), Array(vec![Boolean(true)]))
2963 assert_eq!(from_str(
2969 { \"c\": {\"d\": null} } \
2973 ("a".to_string(), F64(1.0)),
2974 ("b".to_string(), Array(vec![
2976 String("foo\nbar".to_string()),
2978 ("c".to_string(), mk_object(&[("d".to_string(), Null)]))
2985 fn test_decode_struct() {
2988 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
2992 let v: Outer = super::decode(s).unwrap();
2997 Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
3003 #[deriving(Decodable)]
3004 struct FloatStruct {
3009 fn test_decode_struct_with_nan() {
3010 let s = "{\"f\":null,\"a\":[null,123]}";
3011 let obj: FloatStruct = super::decode(s).unwrap();
3012 assert!(obj.f.is_nan());
3013 assert!(obj.a[0].is_nan());
3014 assert_eq!(obj.a[1], 123f64);
3018 fn test_decode_option() {
3019 let value: Option<string::String> = super::decode("null").unwrap();
3020 assert_eq!(value, None);
3022 let value: Option<string::String> = super::decode("\"jodhpurs\"").unwrap();
3023 assert_eq!(value, Some("jodhpurs".to_string()));
3027 fn test_decode_enum() {
3028 let value: Animal = super::decode("\"Dog\"").unwrap();
3029 assert_eq!(value, Dog);
3031 let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
3032 let value: Animal = super::decode(s).unwrap();
3033 assert_eq!(value, Frog("Henry".to_string(), 349));
3037 fn test_decode_map() {
3038 let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
3039 \"fields\":[\"Henry\", 349]}}";
3040 let mut map: TreeMap<string::String, Animal> = super::decode(s).unwrap();
3042 assert_eq!(map.remove(&"a".to_string()), Some(Dog));
3043 assert_eq!(map.remove(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
3047 fn test_multiline_errors() {
3048 assert_eq!(from_str("{\n \"foo\":\n \"bar\""),
3049 Err(SyntaxError(EOFWhileParsingObject, 3u, 8u)));
3052 #[deriving(Decodable)]
3054 struct DecodeStruct {
3058 w: Vec<DecodeStruct>
3060 #[deriving(Decodable)]
3065 fn check_err<T: Decodable<Decoder, DecoderError>>(to_parse: &'static str,
3066 expected: DecoderError) {
3067 let res: DecodeResult<T> = match from_str(to_parse) {
3068 Err(e) => Err(ParseError(e)),
3069 Ok(json) => Decodable::decode(&mut Decoder::new(json))
3072 Ok(_) => panic!("`{}` parsed & decoded ok, expecting error `{}`",
3073 to_parse, expected),
3074 Err(ParseError(e)) => panic!("`{}` is not valid json: {}",
3077 assert_eq!(e, expected);
3082 fn test_decode_errors_struct() {
3083 check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string()));
3084 check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
3085 ExpectedError("Number".to_string(), "true".to_string()));
3086 check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
3087 ExpectedError("Boolean".to_string(), "[]".to_string()));
3088 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
3089 ExpectedError("String".to_string(), "{}".to_string()));
3090 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
3091 ExpectedError("Array".to_string(), "null".to_string()));
3092 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
3093 MissingFieldError("w".to_string()));
3096 fn test_decode_errors_enum() {
3097 check_err::<DecodeEnum>("{}",
3098 MissingFieldError("variant".to_string()));
3099 check_err::<DecodeEnum>("{\"variant\": 1}",
3100 ExpectedError("String".to_string(), "1".to_string()));
3101 check_err::<DecodeEnum>("{\"variant\": \"A\"}",
3102 MissingFieldError("fields".to_string()));
3103 check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
3104 ExpectedError("Array".to_string(), "null".to_string()));
3105 check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
3106 UnknownVariantError("C".to_string()));
3111 let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
3112 let found_str = json_value.find("dog");
3113 assert!(found_str.unwrap().as_string().unwrap() == "cat");
3117 fn test_find_path(){
3118 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3119 let found_str = json_value.find_path(&["dog", "cat", "mouse"]);
3120 assert!(found_str.unwrap().as_string().unwrap() == "cheese");
3125 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
3126 let found_str = json_value.search("mouse").and_then(|j| j.as_string());
3127 assert!(found_str.unwrap() == "cheese");
3132 let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap();
3133 let ref array = json_value["animals"];
3134 assert_eq!(array[0].as_string().unwrap(), "dog");
3135 assert_eq!(array[1].as_string().unwrap(), "cat");
3136 assert_eq!(array[2].as_string().unwrap(), "mouse");
3140 fn test_is_object(){
3141 let json_value = from_str("{}").unwrap();
3142 assert!(json_value.is_object());
3146 fn test_as_object(){
3147 let json_value = from_str("{}").unwrap();
3148 let json_object = json_value.as_object();
3149 assert!(json_object.is_some());
3154 let json_value = from_str("[1, 2, 3]").unwrap();
3155 assert!(json_value.is_array());
3160 let json_value = from_str("[1, 2, 3]").unwrap();
3161 let json_array = json_value.as_array();
3162 let expected_length = 3;
3163 assert!(json_array.is_some() && json_array.unwrap().len() == expected_length);
3167 fn test_is_string(){
3168 let json_value = from_str("\"dog\"").unwrap();
3169 assert!(json_value.is_string());
3173 fn test_as_string(){
3174 let json_value = from_str("\"dog\"").unwrap();
3175 let json_str = json_value.as_string();
3176 let expected_str = "dog";
3177 assert_eq!(json_str, Some(expected_str));
3181 fn test_is_number(){
3182 let json_value = from_str("12").unwrap();
3183 assert!(json_value.is_number());
3188 let json_value = from_str("-12").unwrap();
3189 assert!(json_value.is_i64());
3191 let json_value = from_str("12").unwrap();
3192 assert!(!json_value.is_i64());
3194 let json_value = from_str("12.0").unwrap();
3195 assert!(!json_value.is_i64());
3200 let json_value = from_str("12").unwrap();
3201 assert!(json_value.is_u64());
3203 let json_value = from_str("-12").unwrap();
3204 assert!(!json_value.is_u64());
3206 let json_value = from_str("12.0").unwrap();
3207 assert!(!json_value.is_u64());
3212 let json_value = from_str("12").unwrap();
3213 assert!(!json_value.is_f64());
3215 let json_value = from_str("-12").unwrap();
3216 assert!(!json_value.is_f64());
3218 let json_value = from_str("12.0").unwrap();
3219 assert!(json_value.is_f64());
3221 let json_value = from_str("-12.0").unwrap();
3222 assert!(json_value.is_f64());
3227 let json_value = from_str("-12").unwrap();
3228 let json_num = json_value.as_i64();
3229 assert_eq!(json_num, Some(-12));
3234 let json_value = from_str("12").unwrap();
3235 let json_num = json_value.as_u64();
3236 assert_eq!(json_num, Some(12));
3241 let json_value = from_str("12.0").unwrap();
3242 let json_num = json_value.as_f64();
3243 assert_eq!(json_num, Some(12f64));
3247 fn test_is_boolean(){
3248 let json_value = from_str("false").unwrap();
3249 assert!(json_value.is_boolean());
3253 fn test_as_boolean(){
3254 let json_value = from_str("false").unwrap();
3255 let json_bool = json_value.as_boolean();
3256 let expected_bool = false;
3257 assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
3262 let json_value = from_str("null").unwrap();
3263 assert!(json_value.is_null());
3268 let json_value = from_str("null").unwrap();
3269 let json_null = json_value.as_null();
3270 let expected_null = ();
3271 assert!(json_null.is_some() && json_null.unwrap() == expected_null);
3275 fn test_encode_hashmap_with_numeric_key() {
3276 use std::str::from_utf8;
3277 use std::io::Writer;
3278 use std::collections::HashMap;
3279 let mut hm: HashMap<uint, bool> = HashMap::new();
3281 let mut mem_buf = Vec::new();
3283 let mut encoder = Encoder::new(&mut mem_buf as &mut io::Writer);
3284 hm.encode(&mut encoder).unwrap();
3286 let json_str = from_utf8(mem_buf[]).unwrap();
3287 match from_str(json_str) {
3288 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3289 _ => {} // it parsed and we are good to go
3294 fn test_prettyencode_hashmap_with_numeric_key() {
3295 use std::str::from_utf8;
3296 use std::io::Writer;
3297 use std::collections::HashMap;
3298 let mut hm: HashMap<uint, bool> = HashMap::new();
3300 let mut mem_buf = Vec::new();
3302 let mut encoder = PrettyEncoder::new(&mut mem_buf as &mut io::Writer);
3303 hm.encode(&mut encoder).unwrap()
3305 let json_str = from_utf8(mem_buf[]).unwrap();
3306 match from_str(json_str) {
3307 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3308 _ => {} // it parsed and we are good to go
3313 fn test_prettyencoder_indent_level_param() {
3314 use std::str::from_utf8;
3315 use std::collections::TreeMap;
3317 let mut tree = TreeMap::new();
3319 tree.insert("hello".into_string(), String("guten tag".into_string()));
3320 tree.insert("goodbye".into_string(), String("sayonara".into_string()));
3323 // The following layout below should look a lot like
3324 // the pretty-printed JSON (indent * x)
3327 String("greetings".into_string()), // 1x
3328 Object(tree), // 1x + 2x + 2x + 1x
3330 // End JSON array (7 lines)
3333 // Helper function for counting indents
3334 fn indents(source: &str) -> uint {
3335 let trimmed = source.trim_left_chars(' ');
3336 source.len() - trimmed.len()
3339 // Test up to 4 spaces of indents (more?)
3340 for i in range(0, 4u) {
3341 let mut writer = Vec::new();
3343 let ref mut encoder = PrettyEncoder::new(&mut writer);
3344 encoder.set_indent(i);
3345 json.encode(encoder).unwrap();
3348 let printed = from_utf8(writer[]).unwrap();
3350 // Check for indents at each line
3351 let lines: Vec<&str> = printed.lines().collect();
3352 assert_eq!(lines.len(), 7); // JSON should be 7 lines
3354 assert_eq!(indents(lines[0]), 0 * i); // [
3355 assert_eq!(indents(lines[1]), 1 * i); // "greetings",
3356 assert_eq!(indents(lines[2]), 1 * i); // {
3357 assert_eq!(indents(lines[3]), 2 * i); // "hello": "guten tag",
3358 assert_eq!(indents(lines[4]), 2 * i); // "goodbye": "sayonara"
3359 assert_eq!(indents(lines[5]), 1 * i); // },
3360 assert_eq!(indents(lines[6]), 0 * i); // ]
3362 // Finally, test that the pretty-printed JSON is valid
3363 from_str(printed).ok().expect("Pretty-printed JSON is invalid!");
3368 fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
3369 use std::collections::HashMap;
3371 let json_str = "{\"1\":true}";
3372 let json_obj = match from_str(json_str) {
3373 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3376 let mut decoder = Decoder::new(json_obj);
3377 let _hm: HashMap<uint, bool> = Decodable::decode(&mut decoder).unwrap();
3381 fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
3382 use std::collections::HashMap;
3384 let json_str = "{\"a\":true}";
3385 let json_obj = match from_str(json_str) {
3386 Err(_) => panic!("Unable to parse json_str: {}", json_str),
3389 let mut decoder = Decoder::new(json_obj);
3390 let result: Result<HashMap<uint, bool>, DecoderError> = Decodable::decode(&mut decoder);
3391 assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string())));
3394 fn assert_stream_equal(src: &str,
3395 expected: Vec<(JsonEvent, Vec<StackElement>)>) {
3396 let mut parser = Parser::new(src.chars());
3399 let evt = match parser.next() {
3403 let (ref expected_evt, ref expected_stack) = expected[i];
3404 if !parser.stack().is_equal_to(expected_stack.as_slice()) {
3405 panic!("Parser stack is not equal to {}", expected_stack);
3407 assert_eq!(&evt, expected_evt);
3412 #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
3413 fn test_streaming_parser() {
3414 assert_stream_equal(
3415 r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
3417 (ObjectStart, vec![]),
3418 (StringValue("bar".to_string()), vec![Key("foo")]),
3419 (ArrayStart, vec![Key("array")]),
3420 (U64Value(0), vec![Key("array"), Index(0)]),
3421 (U64Value(1), vec![Key("array"), Index(1)]),
3422 (U64Value(2), vec![Key("array"), Index(2)]),
3423 (U64Value(3), vec![Key("array"), Index(3)]),
3424 (U64Value(4), vec![Key("array"), Index(4)]),
3425 (U64Value(5), vec![Key("array"), Index(5)]),
3426 (ArrayEnd, vec![Key("array")]),
3427 (ArrayStart, vec![Key("idents")]),
3428 (NullValue, vec![Key("idents"), Index(0)]),
3429 (BooleanValue(true), vec![Key("idents"), Index(1)]),
3430 (BooleanValue(false), vec![Key("idents"), Index(2)]),
3431 (ArrayEnd, vec![Key("idents")]),
3432 (ObjectEnd, vec![]),
3436 fn last_event(src: &str) -> JsonEvent {
3437 let mut parser = Parser::new(src.chars());
3438 let mut evt = NullValue;
3440 evt = match parser.next() {
3448 #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
3449 fn test_read_object_streaming() {
3450 assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
3451 assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2)));
3452 assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3453 assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
3454 assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
3456 assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6)));
3457 assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6)));
3458 assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
3459 assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8)));
3460 assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
3461 assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8)));
3463 assert_stream_equal(
3465 vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]
3467 assert_stream_equal(
3470 (ObjectStart, vec![]),
3471 (U64Value(3), vec![Key("a")]),
3472 (ObjectEnd, vec![]),
3475 assert_stream_equal(
3476 "{ \"a\": null, \"b\" : true }",
3478 (ObjectStart, vec![]),
3479 (NullValue, vec![Key("a")]),
3480 (BooleanValue(true), vec![Key("b")]),
3481 (ObjectEnd, vec![]),
3484 assert_stream_equal(
3485 "{\"a\" : 1.0 ,\"b\": [ true ]}",
3487 (ObjectStart, vec![]),
3488 (F64Value(1.0), vec![Key("a")]),
3489 (ArrayStart, vec![Key("b")]),
3490 (BooleanValue(true),vec![Key("b"), Index(0)]),
3491 (ArrayEnd, vec![Key("b")]),
3492 (ObjectEnd, vec![]),
3495 assert_stream_equal(
3501 { "c": {"d": null} }
3505 (ObjectStart, vec![]),
3506 (F64Value(1.0), vec![Key("a")]),
3507 (ArrayStart, vec![Key("b")]),
3508 (BooleanValue(true), vec![Key("b"), Index(0)]),
3509 (StringValue("foo\nbar".to_string()), vec![Key("b"), Index(1)]),
3510 (ObjectStart, vec![Key("b"), Index(2)]),
3511 (ObjectStart, vec![Key("b"), Index(2), Key("c")]),
3512 (NullValue, vec![Key("b"), Index(2), Key("c"), Key("d")]),
3513 (ObjectEnd, vec![Key("b"), Index(2), Key("c")]),
3514 (ObjectEnd, vec![Key("b"), Index(2)]),
3515 (ArrayEnd, vec![Key("b")]),
3516 (ObjectEnd, vec![]),
3521 #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064)
3522 fn test_read_array_streaming() {
3523 assert_stream_equal(
3526 (ArrayStart, vec![]),
3530 assert_stream_equal(
3533 (ArrayStart, vec![]),
3537 assert_stream_equal(
3540 (ArrayStart, vec![]),
3541 (BooleanValue(true), vec![Index(0)]),
3545 assert_stream_equal(
3548 (ArrayStart, vec![]),
3549 (BooleanValue(false), vec![Index(0)]),
3553 assert_stream_equal(
3556 (ArrayStart, vec![]),
3557 (NullValue, vec![Index(0)]),
3561 assert_stream_equal(
3564 (ArrayStart, vec![]),
3565 (U64Value(3), vec![Index(0)]),
3566 (U64Value(1), vec![Index(1)]),
3570 assert_stream_equal(
3573 (ArrayStart, vec![]),
3574 (U64Value(3), vec![Index(0)]),
3575 (U64Value(2), vec![Index(1)]),
3579 assert_stream_equal(
3582 (ArrayStart, vec![]),
3583 (U64Value(2), vec![Index(0)]),
3584 (ArrayStart, vec![Index(1)]),
3585 (U64Value(4), vec![Index(1), Index(0)]),
3586 (U64Value(1), vec![Index(1), Index(1)]),
3587 (ArrayEnd, vec![Index(1)]),
3592 assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2)));
3594 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
3595 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
3596 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
3597 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3598 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
3602 fn test_trailing_characters_streaming() {
3603 assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3604 assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5)));
3605 assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
3606 assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2)));
3607 assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3608 assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
3611 fn test_read_identifiers_streaming() {
3612 assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
3613 assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
3614 assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));
3616 assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3617 assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3618 assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3619 assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
3620 assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2)));
3621 assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3)));
3626 let mut stack = Stack::new();
3628 assert!(stack.is_empty());
3629 assert!(stack.len() == 0);
3630 assert!(!stack.last_is_index());
3632 stack.push_index(0);
3635 assert!(stack.len() == 1);
3636 assert!(stack.is_equal_to(&[Index(1)]));
3637 assert!(stack.starts_with(&[Index(1)]));
3638 assert!(stack.ends_with(&[Index(1)]));
3639 assert!(stack.last_is_index());
3640 assert!(stack.get(0) == Index(1));
3642 stack.push_key("foo".to_string());
3644 assert!(stack.len() == 2);
3645 assert!(stack.is_equal_to(&[Index(1), Key("foo")]));
3646 assert!(stack.starts_with(&[Index(1), Key("foo")]));
3647 assert!(stack.starts_with(&[Index(1)]));
3648 assert!(stack.ends_with(&[Index(1), Key("foo")]));
3649 assert!(stack.ends_with(&[Key("foo")]));
3650 assert!(!stack.last_is_index());
3651 assert!(stack.get(0) == Index(1));
3652 assert!(stack.get(1) == Key("foo"));
3654 stack.push_key("bar".to_string());
3656 assert!(stack.len() == 3);
3657 assert!(stack.is_equal_to(&[Index(1), Key("foo"), Key("bar")]));
3658 assert!(stack.starts_with(&[Index(1)]));
3659 assert!(stack.starts_with(&[Index(1), Key("foo")]));
3660 assert!(stack.starts_with(&[Index(1), Key("foo"), Key("bar")]));
3661 assert!(stack.ends_with(&[Key("bar")]));
3662 assert!(stack.ends_with(&[Key("foo"), Key("bar")]));
3663 assert!(stack.ends_with(&[Index(1), Key("foo"), Key("bar")]));
3664 assert!(!stack.last_is_index());
3665 assert!(stack.get(0) == Index(1));
3666 assert!(stack.get(1) == Key("foo"));
3667 assert!(stack.get(2) == Key("bar"));
3671 assert!(stack.len() == 2);
3672 assert!(stack.is_equal_to(&[Index(1), Key("foo")]));
3673 assert!(stack.starts_with(&[Index(1), Key("foo")]));
3674 assert!(stack.starts_with(&[Index(1)]));
3675 assert!(stack.ends_with(&[Index(1), Key("foo")]));
3676 assert!(stack.ends_with(&[Key("foo")]));
3677 assert!(!stack.last_is_index());
3678 assert!(stack.get(0) == Index(1));
3679 assert!(stack.get(1) == Key("foo"));
3684 use std::collections::{HashMap,TreeMap};
3687 let array2 = Array(vec!(U64(1), U64(2)));
3688 let array3 = Array(vec!(U64(1), U64(2), U64(3)));
3690 let mut tree_map = TreeMap::new();
3691 tree_map.insert("a".to_string(), U64(1));
3692 tree_map.insert("b".to_string(), U64(2));
3696 assert_eq!(array2.to_json(), array2);
3697 assert_eq!(object.to_json(), object);
3698 assert_eq!(3_i.to_json(), I64(3));
3699 assert_eq!(4_i8.to_json(), I64(4));
3700 assert_eq!(5_i16.to_json(), I64(5));
3701 assert_eq!(6_i32.to_json(), I64(6));
3702 assert_eq!(7_i64.to_json(), I64(7));
3703 assert_eq!(8_u.to_json(), U64(8));
3704 assert_eq!(9_u8.to_json(), U64(9));
3705 assert_eq!(10_u16.to_json(), U64(10));
3706 assert_eq!(11_u32.to_json(), U64(11));
3707 assert_eq!(12_u64.to_json(), U64(12));
3708 assert_eq!(13.0_f32.to_json(), F64(13.0_f64));
3709 assert_eq!(14.0_f64.to_json(), F64(14.0_f64));
3710 assert_eq!(().to_json(), Null);
3711 assert_eq!(f32::INFINITY.to_json(), Null);
3712 assert_eq!(f64::NAN.to_json(), Null);
3713 assert_eq!(true.to_json(), Boolean(true));
3714 assert_eq!(false.to_json(), Boolean(false));
3715 assert_eq!("abc".to_json(), String("abc".into_string()));
3716 assert_eq!("abc".into_string().to_json(), String("abc".into_string()));
3717 assert_eq!((1u, 2u).to_json(), array2);
3718 assert_eq!((1u, 2u, 3u).to_json(), array3);
3719 assert_eq!([1u, 2].to_json(), array2);
3720 assert_eq!((&[1u, 2, 3]).to_json(), array3);
3721 assert_eq!((vec![1u, 2]).to_json(), array2);
3722 assert_eq!(vec!(1u, 2, 3).to_json(), array3);
3723 let mut tree_map = TreeMap::new();
3724 tree_map.insert("a".to_string(), 1u);
3725 tree_map.insert("b".to_string(), 2);
3726 assert_eq!(tree_map.to_json(), object);
3727 let mut hash_map = HashMap::new();
3728 hash_map.insert("a".to_string(), 1u);
3729 hash_map.insert("b".to_string(), 2);
3730 assert_eq!(hash_map.to_json(), object);
3731 assert_eq!(Some(15i).to_json(), I64(15));
3732 assert_eq!(Some(15u).to_json(), U64(15));
3733 assert_eq!(None::<int>.to_json(), Null);
3737 fn bench_streaming_small(b: &mut Bencher) {
3739 let mut parser = Parser::new(
3745 { "c": {"d": null} }
3750 match parser.next() {
3758 fn bench_small(b: &mut Bencher) {
3760 let _ = from_str(r#"{
3765 { "c": {"d": null} }
3771 fn big_json() -> string::String {
3772 let mut src = "[\n".to_string();
3773 for _ in range(0i, 500) {
3774 src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \
3777 src.push_str("{}]");
3782 fn bench_streaming_large(b: &mut Bencher) {
3783 let src = big_json();
3785 let mut parser = Parser::new(src.chars());
3787 match parser.next() {
3795 fn bench_large(b: &mut Bencher) {
3796 let src = big_json();
3797 b.iter( || { let _ = from_str(src.as_slice()); });