1 // Rust JSON serialization library.
2 // Copyright (c) 2011 Google Inc.
4 #![forbid(non_camel_case_types)]
5 #![allow(missing_docs)]
7 //! JSON parsing and serialization
11 //! JSON (JavaScript Object Notation) is a way to write data in Javascript.
12 //! Like XML, it allows to encode structured data in a text format that can be easily read by humans
13 //! Its simple syntax and native compatibility with JavaScript have made it a widely used format.
15 //! Data types that can be encoded are JavaScript types (see the `Json` enum for more details):
17 //! * `Boolean`: equivalent to rust's `bool`
18 //! * `Number`: equivalent to rust's `f64`
19 //! * `String`: equivalent to rust's `String`
20 //! * `Array`: equivalent to rust's `Vec<T>`, but also allowing objects of different types in the
22 //! * `Object`: equivalent to rust's `BTreeMap<String, json::Json>`
25 //! An object is a series of string keys mapping to values, in `"key": value` format.
26 //! Arrays are enclosed in square brackets ([ ... ]) and objects in curly brackets ({ ... }).
27 //! A simple JSON document encoding a person, their age, address and phone numbers could look like
31 //! "FirstName": "John",
32 //! "LastName": "Doe",
35 //! "Street": "Downing Street 10",
37 //! "Country": "Great Britain"
46 //! # Rust Type-based Encoding and Decoding
48 //! Rust provides a mechanism for low boilerplate encoding & decoding of values to and from JSON via
49 //! the serialization API.
50 //! To be able to encode a piece of data, it must implement the `serialize::Encodable` trait.
51 //! To be able to decode a piece of data, it must implement the `serialize::Decodable` trait.
52 //! The Rust compiler provides an annotation to automatically generate the code for these traits:
53 //! `#[derive(Decodable, Encodable)]`
55 //! The JSON API provides an enum `json::Json` and a trait `ToJson` to encode objects.
56 //! The `ToJson` trait provides a `to_json` method to convert an object into a `json::Json` value.
57 //! A `json::Json` value can be encoded as a string or buffer using the functions described above.
58 //! You can also use the `json::Encoder` object, which implements the `Encoder` trait.
60 //! When using `ToJson` the `Encodable` trait implementation is not mandatory.
64 //! ## Using Autoserialization
66 //! Create a struct called `TestStruct` and serialize and deserialize it to and from JSON using the
67 //! serialization API, using the derived serialization code.
70 //! # #![feature(rustc_private)]
71 //! use rustc_macros::{Decodable, Encodable};
72 //! use rustc_serialize::json;
74 //! // Automatically generate `Decodable` and `Encodable` trait implementations
75 //! #[derive(Decodable, Encodable)]
76 //! pub struct TestStruct {
79 //! data_vector: Vec<u8>,
82 //! let object = TestStruct {
84 //! data_str: "homura".to_string(),
85 //! data_vector: vec![2,3,4,5],
88 //! // Serialize using `json::encode`
89 //! let encoded = json::encode(&object).unwrap();
91 //! // Deserialize using `json::decode`
92 //! let decoded: TestStruct = json::decode(&encoded[..]).unwrap();
95 //! ## Using the `ToJson` trait
97 //! The examples above use the `ToJson` trait to generate the JSON string, which is required
98 //! for custom mappings.
100 //! ### Simple example of `ToJson` usage
103 //! # #![feature(rustc_private)]
104 //! use rustc_macros::Encodable;
105 //! use rustc_serialize::json::{self, ToJson, Json};
107 //! // A custom data structure
108 //! struct ComplexNum {
113 //! // JSON value representation
114 //! impl ToJson for ComplexNum {
115 //! fn to_json(&self) -> Json {
116 //! Json::String(format!("{}+{}i", self.a, self.b))
120 //! // Only generate `Encodable` trait implementation
121 //! #[derive(Encodable)]
122 //! pub struct ComplexNumRecord {
128 //! let num = ComplexNum { a: 0.0001, b: 12.539 };
129 //! let data: String = json::encode(&ComplexNumRecord{
131 //! dsc: "test".to_string(),
132 //! val: num.to_json(),
134 //! println!("data: {}", data);
135 //! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539i"};
138 //! ### Verbose example of `ToJson` usage
141 //! # #![feature(rustc_private)]
142 //! use rustc_macros::Decodable;
143 //! use std::collections::BTreeMap;
144 //! use rustc_serialize::json::{self, Json, ToJson};
146 //! // Only generate `Decodable` trait implementation
147 //! #[derive(Decodable)]
148 //! pub struct TestStruct {
150 //! data_str: String,
151 //! data_vector: Vec<u8>,
154 //! // Specify encoding method manually
155 //! impl ToJson for TestStruct {
156 //! fn to_json(&self) -> Json {
157 //! let mut d = BTreeMap::new();
158 //! // All standard types implement `to_json()`, so use it
159 //! d.insert("data_int".to_string(), self.data_int.to_json());
160 //! d.insert("data_str".to_string(), self.data_str.to_json());
161 //! d.insert("data_vector".to_string(), self.data_vector.to_json());
166 //! // Serialize using `ToJson`
167 //! let input_data = TestStruct {
169 //! data_str: "madoka".to_string(),
170 //! data_vector: vec![2,3,4,5],
172 //! let json_obj: Json = input_data.to_json();
173 //! let json_str: String = json_obj.to_string();
175 //! // Deserialize like before
176 //! let decoded: TestStruct = json::decode(&json_str).unwrap();
179 use self::DecoderError::*;
180 use self::ErrorCode::*;
181 use self::InternalStackElement::*;
182 use self::JsonEvent::*;
183 use self::ParserError::*;
184 use self::ParserState::*;
186 use std::borrow::Cow;
187 use std::collections::{BTreeMap, HashMap};
189 use std::io::prelude::*;
191 use std::num::FpCategory as Fp;
193 use std::str::FromStr;
195 use std::{char, fmt, str};
197 use crate::Encodable;
199 /// Represents a json value
200 #[derive(Clone, PartialEq, PartialOrd, Debug)]
205 String(string::String),
208 Object(self::Object),
212 pub type Array = Vec<Json>;
213 pub type Object = BTreeMap<string::String, Json>;
215 pub struct PrettyJson<'a> {
219 pub struct AsJson<'a, T> {
222 pub struct AsPrettyJson<'a, T> {
224 indent: Option<usize>,
227 /// The errors that can arise while parsing a JSON stream.
228 #[derive(Clone, Copy, PartialEq, Debug)]
232 EOFWhileParsingObject,
233 EOFWhileParsingArray,
234 EOFWhileParsingValue,
235 EOFWhileParsingString,
241 InvalidUnicodeCodePoint,
242 LoneLeadingSurrogateInHexEscape,
243 UnexpectedEndOfHexEscape,
249 #[derive(Clone, PartialEq, Debug)]
250 pub enum ParserError {
252 SyntaxError(ErrorCode, usize, usize),
253 IoError(io::ErrorKind, String),
256 // Builder and Parser have the same errors.
257 pub type BuilderError = ParserError;
259 #[derive(Clone, PartialEq, Debug)]
260 pub enum DecoderError {
261 ParseError(ParserError),
262 ExpectedError(string::String, string::String),
263 MissingFieldError(string::String),
264 UnknownVariantError(string::String),
265 ApplicationError(string::String),
268 #[derive(Copy, Clone, Debug)]
269 pub enum EncoderError {
270 FmtError(fmt::Error),
274 /// Returns a readable error string for a given error code.
275 pub fn error_str(error: ErrorCode) -> &'static str {
277 InvalidSyntax => "invalid syntax",
278 InvalidNumber => "invalid number",
279 EOFWhileParsingObject => "EOF While parsing object",
280 EOFWhileParsingArray => "EOF While parsing array",
281 EOFWhileParsingValue => "EOF While parsing value",
282 EOFWhileParsingString => "EOF While parsing string",
283 KeyMustBeAString => "key must be a string",
284 ExpectedColon => "expected `:`",
285 TrailingCharacters => "trailing characters",
286 TrailingComma => "trailing comma",
287 InvalidEscape => "invalid escape",
288 UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)",
289 NotFourDigit => "invalid \\u{ esc}ape (not four digits)",
290 NotUtf8 => "contents not utf-8",
291 InvalidUnicodeCodePoint => "invalid Unicode code point",
292 LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
293 UnexpectedEndOfHexEscape => "unexpected end of hex escape",
297 /// Shortcut function to decode a JSON `&str` into an object
298 pub fn decode<T: crate::Decodable<Decoder>>(s: &str) -> DecodeResult<T> {
299 let json = match from_str(s) {
301 Err(e) => return Err(ParseError(e)),
304 let mut decoder = Decoder::new(json);
305 crate::Decodable::decode(&mut decoder)
308 /// Shortcut function to encode a `T` into a JSON `String`
309 pub fn encode<T: for<'r> crate::Encodable<Encoder<'r>>>(
311 ) -> Result<string::String, EncoderError> {
312 let mut s = String::new();
314 let mut encoder = Encoder::new(&mut s);
315 object.encode(&mut encoder)?;
320 impl fmt::Display for ErrorCode {
321 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322 error_str(*self).fmt(f)
326 fn io_error_to_error(io: io::Error) -> ParserError {
327 IoError(io.kind(), io.to_string())
330 impl fmt::Display for ParserError {
331 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
332 // FIXME this should be a nicer error
333 fmt::Debug::fmt(self, f)
337 impl fmt::Display for DecoderError {
338 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
339 // FIXME this should be a nicer error
340 fmt::Debug::fmt(self, f)
344 impl std::error::Error for DecoderError {}
346 impl fmt::Display for EncoderError {
347 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348 // FIXME this should be a nicer error
349 fmt::Debug::fmt(self, f)
353 impl std::error::Error for EncoderError {}
355 impl From<fmt::Error> for EncoderError {
356 /// Converts a [`fmt::Error`] into `EncoderError`
358 /// This conversion does not allocate memory.
359 fn from(err: fmt::Error) -> EncoderError {
360 EncoderError::FmtError(err)
364 pub type EncodeResult = Result<(), EncoderError>;
365 pub type DecodeResult<T> = Result<T, DecoderError>;
367 fn escape_str(wr: &mut dyn fmt::Write, v: &str) -> EncodeResult {
372 for (i, byte) in v.bytes().enumerate() {
373 let escaped = match byte {
376 b'\x00' => "\\u0000",
377 b'\x01' => "\\u0001",
378 b'\x02' => "\\u0002",
379 b'\x03' => "\\u0003",
380 b'\x04' => "\\u0004",
381 b'\x05' => "\\u0005",
382 b'\x06' => "\\u0006",
383 b'\x07' => "\\u0007",
387 b'\x0b' => "\\u000b",
390 b'\x0e' => "\\u000e",
391 b'\x0f' => "\\u000f",
392 b'\x10' => "\\u0010",
393 b'\x11' => "\\u0011",
394 b'\x12' => "\\u0012",
395 b'\x13' => "\\u0013",
396 b'\x14' => "\\u0014",
397 b'\x15' => "\\u0015",
398 b'\x16' => "\\u0016",
399 b'\x17' => "\\u0017",
400 b'\x18' => "\\u0018",
401 b'\x19' => "\\u0019",
402 b'\x1a' => "\\u001a",
403 b'\x1b' => "\\u001b",
404 b'\x1c' => "\\u001c",
405 b'\x1d' => "\\u001d",
406 b'\x1e' => "\\u001e",
407 b'\x1f' => "\\u001f",
408 b'\x7f' => "\\u007f",
415 wr.write_str(&v[start..i])?;
418 wr.write_str(escaped)?;
423 if start != v.len() {
424 wr.write_str(&v[start..])?;
431 fn escape_char(writer: &mut dyn fmt::Write, v: char) -> EncodeResult {
432 escape_str(writer, v.encode_utf8(&mut [0; 4]))
435 fn spaces(wr: &mut dyn fmt::Write, mut n: usize) -> EncodeResult {
436 const BUF: &str = " ";
438 while n >= BUF.len() {
444 wr.write_str(&BUF[..n])?;
449 fn fmt_number_or_null(v: f64) -> string::String {
451 Fp::Nan | Fp::Infinite => string::String::from("null"),
452 _ if v.fract() != 0f64 => v.to_string(),
453 _ => v.to_string() + ".0",
457 /// A structure for implementing serialization to JSON.
458 pub struct Encoder<'a> {
459 writer: &'a mut (dyn fmt::Write + 'a),
460 is_emitting_map_key: bool,
463 impl<'a> Encoder<'a> {
464 /// Creates a new JSON encoder whose output will be written to the writer
466 pub fn new(writer: &'a mut dyn fmt::Write) -> Encoder<'a> {
467 Encoder { writer, is_emitting_map_key: false }
471 macro_rules! emit_enquoted_if_mapkey {
472 ($enc:ident,$e:expr) => {{
473 if $enc.is_emitting_map_key {
474 write!($enc.writer, "\"{}\"", $e)?;
476 write!($enc.writer, "{}", $e)?;
482 impl<'a> crate::Encoder for Encoder<'a> {
483 type Error = EncoderError;
485 fn emit_unit(&mut self) -> EncodeResult {
486 if self.is_emitting_map_key {
487 return Err(EncoderError::BadHashmapKey);
489 write!(self.writer, "null")?;
493 fn emit_usize(&mut self, v: usize) -> EncodeResult {
494 emit_enquoted_if_mapkey!(self, v)
496 fn emit_u128(&mut self, v: u128) -> EncodeResult {
497 emit_enquoted_if_mapkey!(self, v)
499 fn emit_u64(&mut self, v: u64) -> EncodeResult {
500 emit_enquoted_if_mapkey!(self, v)
502 fn emit_u32(&mut self, v: u32) -> EncodeResult {
503 emit_enquoted_if_mapkey!(self, v)
505 fn emit_u16(&mut self, v: u16) -> EncodeResult {
506 emit_enquoted_if_mapkey!(self, v)
508 fn emit_u8(&mut self, v: u8) -> EncodeResult {
509 emit_enquoted_if_mapkey!(self, v)
512 fn emit_isize(&mut self, v: isize) -> EncodeResult {
513 emit_enquoted_if_mapkey!(self, v)
515 fn emit_i128(&mut self, v: i128) -> EncodeResult {
516 emit_enquoted_if_mapkey!(self, v)
518 fn emit_i64(&mut self, v: i64) -> EncodeResult {
519 emit_enquoted_if_mapkey!(self, v)
521 fn emit_i32(&mut self, v: i32) -> EncodeResult {
522 emit_enquoted_if_mapkey!(self, v)
524 fn emit_i16(&mut self, v: i16) -> EncodeResult {
525 emit_enquoted_if_mapkey!(self, v)
527 fn emit_i8(&mut self, v: i8) -> EncodeResult {
528 emit_enquoted_if_mapkey!(self, v)
531 fn emit_bool(&mut self, v: bool) -> EncodeResult {
532 if self.is_emitting_map_key {
533 return Err(EncoderError::BadHashmapKey);
536 write!(self.writer, "true")?;
538 write!(self.writer, "false")?;
543 fn emit_f64(&mut self, v: f64) -> EncodeResult {
544 emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
546 fn emit_f32(&mut self, v: f32) -> EncodeResult {
547 self.emit_f64(f64::from(v))
550 fn emit_char(&mut self, v: char) -> EncodeResult {
551 escape_char(self.writer, v)
553 fn emit_str(&mut self, v: &str) -> EncodeResult {
554 escape_str(self.writer, v)
556 fn emit_raw_bytes(&mut self, s: &[u8]) -> Result<(), Self::Error> {
563 fn emit_enum<F>(&mut self, f: F) -> EncodeResult
565 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
570 fn emit_enum_variant<F>(&mut self, name: &str, _id: usize, cnt: usize, f: F) -> EncodeResult
572 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
574 // enums are encoded as strings or objects
576 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
578 escape_str(self.writer, name)
580 if self.is_emitting_map_key {
581 return Err(EncoderError::BadHashmapKey);
583 write!(self.writer, "{{\"variant\":")?;
584 escape_str(self.writer, name)?;
585 write!(self.writer, ",\"fields\":[")?;
587 write!(self.writer, "]}}")?;
592 fn emit_enum_variant_arg<F>(&mut self, first: bool, f: F) -> EncodeResult
594 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
596 if self.is_emitting_map_key {
597 return Err(EncoderError::BadHashmapKey);
600 write!(self.writer, ",")?;
605 fn emit_struct<F>(&mut self, _: bool, f: F) -> EncodeResult
607 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
609 if self.is_emitting_map_key {
610 return Err(EncoderError::BadHashmapKey);
612 write!(self.writer, "{{")?;
614 write!(self.writer, "}}")?;
618 fn emit_struct_field<F>(&mut self, name: &str, first: bool, f: F) -> EncodeResult
620 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
622 if self.is_emitting_map_key {
623 return Err(EncoderError::BadHashmapKey);
626 write!(self.writer, ",")?;
628 escape_str(self.writer, name)?;
629 write!(self.writer, ":")?;
633 fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult
635 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
637 if self.is_emitting_map_key {
638 return Err(EncoderError::BadHashmapKey);
640 self.emit_seq(len, f)
642 fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
644 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
646 if self.is_emitting_map_key {
647 return Err(EncoderError::BadHashmapKey);
649 self.emit_seq_elt(idx, f)
652 fn emit_option<F>(&mut self, f: F) -> EncodeResult
654 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
656 if self.is_emitting_map_key {
657 return Err(EncoderError::BadHashmapKey);
661 fn emit_option_none(&mut self) -> EncodeResult {
662 if self.is_emitting_map_key {
663 return Err(EncoderError::BadHashmapKey);
667 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult
669 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
671 if self.is_emitting_map_key {
672 return Err(EncoderError::BadHashmapKey);
677 fn emit_seq<F>(&mut self, _len: usize, f: F) -> EncodeResult
679 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
681 if self.is_emitting_map_key {
682 return Err(EncoderError::BadHashmapKey);
684 write!(self.writer, "[")?;
686 write!(self.writer, "]")?;
690 fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult
692 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
694 if self.is_emitting_map_key {
695 return Err(EncoderError::BadHashmapKey);
698 write!(self.writer, ",")?;
703 fn emit_map<F>(&mut self, _len: usize, f: F) -> EncodeResult
705 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
707 if self.is_emitting_map_key {
708 return Err(EncoderError::BadHashmapKey);
710 write!(self.writer, "{{")?;
712 write!(self.writer, "}}")?;
716 fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult
718 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
720 if self.is_emitting_map_key {
721 return Err(EncoderError::BadHashmapKey);
724 write!(self.writer, ",")?
726 self.is_emitting_map_key = true;
728 self.is_emitting_map_key = false;
732 fn emit_map_elt_val<F>(&mut self, f: F) -> EncodeResult
734 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
736 if self.is_emitting_map_key {
737 return Err(EncoderError::BadHashmapKey);
739 write!(self.writer, ":")?;
744 /// Another encoder for JSON, but prints out human-readable JSON instead of
746 pub struct PrettyEncoder<'a> {
747 writer: &'a mut (dyn fmt::Write + 'a),
750 is_emitting_map_key: bool,
753 impl<'a> PrettyEncoder<'a> {
754 /// Creates a new encoder whose output will be written to the specified writer
755 pub fn new(writer: &'a mut dyn fmt::Write) -> PrettyEncoder<'a> {
756 PrettyEncoder { writer, curr_indent: 0, indent: 2, is_emitting_map_key: false }
759 /// Sets the number of spaces to indent for each level.
760 /// This is safe to set during encoding.
761 pub fn set_indent(&mut self, indent: usize) {
762 // self.indent very well could be 0 so we need to use checked division.
763 let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
764 self.indent = indent;
765 self.curr_indent = level * self.indent;
769 impl<'a> crate::Encoder for PrettyEncoder<'a> {
770 type Error = EncoderError;
772 fn emit_unit(&mut self) -> EncodeResult {
773 if self.is_emitting_map_key {
774 return Err(EncoderError::BadHashmapKey);
776 write!(self.writer, "null")?;
780 fn emit_usize(&mut self, v: usize) -> EncodeResult {
781 emit_enquoted_if_mapkey!(self, v)
783 fn emit_u128(&mut self, v: u128) -> EncodeResult {
784 emit_enquoted_if_mapkey!(self, v)
786 fn emit_u64(&mut self, v: u64) -> EncodeResult {
787 emit_enquoted_if_mapkey!(self, v)
789 fn emit_u32(&mut self, v: u32) -> EncodeResult {
790 emit_enquoted_if_mapkey!(self, v)
792 fn emit_u16(&mut self, v: u16) -> EncodeResult {
793 emit_enquoted_if_mapkey!(self, v)
795 fn emit_u8(&mut self, v: u8) -> EncodeResult {
796 emit_enquoted_if_mapkey!(self, v)
799 fn emit_isize(&mut self, v: isize) -> EncodeResult {
800 emit_enquoted_if_mapkey!(self, v)
802 fn emit_i128(&mut self, v: i128) -> EncodeResult {
803 emit_enquoted_if_mapkey!(self, v)
805 fn emit_i64(&mut self, v: i64) -> EncodeResult {
806 emit_enquoted_if_mapkey!(self, v)
808 fn emit_i32(&mut self, v: i32) -> EncodeResult {
809 emit_enquoted_if_mapkey!(self, v)
811 fn emit_i16(&mut self, v: i16) -> EncodeResult {
812 emit_enquoted_if_mapkey!(self, v)
814 fn emit_i8(&mut self, v: i8) -> EncodeResult {
815 emit_enquoted_if_mapkey!(self, v)
818 fn emit_bool(&mut self, v: bool) -> EncodeResult {
819 if self.is_emitting_map_key {
820 return Err(EncoderError::BadHashmapKey);
823 write!(self.writer, "true")?;
825 write!(self.writer, "false")?;
830 fn emit_f64(&mut self, v: f64) -> EncodeResult {
831 emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
833 fn emit_f32(&mut self, v: f32) -> EncodeResult {
834 self.emit_f64(f64::from(v))
837 fn emit_char(&mut self, v: char) -> EncodeResult {
838 escape_char(self.writer, v)
840 fn emit_str(&mut self, v: &str) -> EncodeResult {
841 escape_str(self.writer, v)
843 fn emit_raw_bytes(&mut self, s: &[u8]) -> Result<(), Self::Error> {
850 fn emit_enum<F>(&mut self, f: F) -> EncodeResult
852 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
857 fn emit_enum_variant<F>(&mut self, name: &str, _id: usize, cnt: usize, f: F) -> EncodeResult
859 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
862 escape_str(self.writer, name)
864 if self.is_emitting_map_key {
865 return Err(EncoderError::BadHashmapKey);
867 writeln!(self.writer, "{{")?;
868 self.curr_indent += self.indent;
869 spaces(self.writer, self.curr_indent)?;
870 write!(self.writer, "\"variant\": ")?;
871 escape_str(self.writer, name)?;
872 writeln!(self.writer, ",")?;
873 spaces(self.writer, self.curr_indent)?;
874 writeln!(self.writer, "\"fields\": [")?;
875 self.curr_indent += self.indent;
877 self.curr_indent -= self.indent;
878 writeln!(self.writer)?;
879 spaces(self.writer, self.curr_indent)?;
880 self.curr_indent -= self.indent;
881 writeln!(self.writer, "]")?;
882 spaces(self.writer, self.curr_indent)?;
883 write!(self.writer, "}}")?;
888 fn emit_enum_variant_arg<F>(&mut self, first: bool, f: F) -> EncodeResult
890 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
892 if self.is_emitting_map_key {
893 return Err(EncoderError::BadHashmapKey);
896 writeln!(self.writer, ",")?;
898 spaces(self.writer, self.curr_indent)?;
902 fn emit_struct<F>(&mut self, no_fields: bool, f: F) -> EncodeResult
904 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
906 if self.is_emitting_map_key {
907 return Err(EncoderError::BadHashmapKey);
910 write!(self.writer, "{{}}")?;
912 write!(self.writer, "{{")?;
913 self.curr_indent += self.indent;
915 self.curr_indent -= self.indent;
916 writeln!(self.writer)?;
917 spaces(self.writer, self.curr_indent)?;
918 write!(self.writer, "}}")?;
923 fn emit_struct_field<F>(&mut self, name: &str, first: bool, f: F) -> EncodeResult
925 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
927 if self.is_emitting_map_key {
928 return Err(EncoderError::BadHashmapKey);
931 writeln!(self.writer)?;
933 writeln!(self.writer, ",")?;
935 spaces(self.writer, self.curr_indent)?;
936 escape_str(self.writer, name)?;
937 write!(self.writer, ": ")?;
941 fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult
943 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
945 if self.is_emitting_map_key {
946 return Err(EncoderError::BadHashmapKey);
948 self.emit_seq(len, f)
950 fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
952 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
954 if self.is_emitting_map_key {
955 return Err(EncoderError::BadHashmapKey);
957 self.emit_seq_elt(idx, f)
960 fn emit_option<F>(&mut self, f: F) -> EncodeResult
962 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
964 if self.is_emitting_map_key {
965 return Err(EncoderError::BadHashmapKey);
969 fn emit_option_none(&mut self) -> EncodeResult {
970 if self.is_emitting_map_key {
971 return Err(EncoderError::BadHashmapKey);
975 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult
977 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
979 if self.is_emitting_map_key {
980 return Err(EncoderError::BadHashmapKey);
985 fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodeResult
987 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
989 if self.is_emitting_map_key {
990 return Err(EncoderError::BadHashmapKey);
993 write!(self.writer, "[]")?;
995 write!(self.writer, "[")?;
996 self.curr_indent += self.indent;
998 self.curr_indent -= self.indent;
999 writeln!(self.writer)?;
1000 spaces(self.writer, self.curr_indent)?;
1001 write!(self.writer, "]")?;
1006 fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult
1008 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1010 if self.is_emitting_map_key {
1011 return Err(EncoderError::BadHashmapKey);
1014 writeln!(self.writer)?;
1016 writeln!(self.writer, ",")?;
1018 spaces(self.writer, self.curr_indent)?;
1022 fn emit_map<F>(&mut self, len: usize, f: F) -> EncodeResult
1024 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1026 if self.is_emitting_map_key {
1027 return Err(EncoderError::BadHashmapKey);
1030 write!(self.writer, "{{}}")?;
1032 write!(self.writer, "{{")?;
1033 self.curr_indent += self.indent;
1035 self.curr_indent -= self.indent;
1036 writeln!(self.writer)?;
1037 spaces(self.writer, self.curr_indent)?;
1038 write!(self.writer, "}}")?;
1043 fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult
1045 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1047 if self.is_emitting_map_key {
1048 return Err(EncoderError::BadHashmapKey);
1051 writeln!(self.writer)?;
1053 writeln!(self.writer, ",")?;
1055 spaces(self.writer, self.curr_indent)?;
1056 self.is_emitting_map_key = true;
1058 self.is_emitting_map_key = false;
1062 fn emit_map_elt_val<F>(&mut self, f: F) -> EncodeResult
1064 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1066 if self.is_emitting_map_key {
1067 return Err(EncoderError::BadHashmapKey);
1069 write!(self.writer, ": ")?;
1074 impl<E: crate::Encoder> Encodable<E> for Json {
1075 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
1077 Json::I64(v) => v.encode(e),
1078 Json::U64(v) => v.encode(e),
1079 Json::F64(v) => v.encode(e),
1080 Json::String(ref v) => v.encode(e),
1081 Json::Boolean(v) => v.encode(e),
1082 Json::Array(ref v) => v.encode(e),
1083 Json::Object(ref v) => v.encode(e),
1084 Json::Null => e.emit_unit(),
1089 /// Creates an `AsJson` wrapper which can be used to print a value as JSON
1090 /// on-the-fly via `write!`
1091 pub fn as_json<T>(t: &T) -> AsJson<'_, T> {
1095 /// Creates an `AsPrettyJson` wrapper which can be used to print a value as JSON
1096 /// on-the-fly via `write!`
1097 pub fn as_pretty_json<T>(t: &T) -> AsPrettyJson<'_, T> {
1098 AsPrettyJson { inner: t, indent: None }
1102 /// Borrow this json object as a pretty object to generate a pretty
1103 /// representation for it via `Display`.
1104 pub fn pretty(&self) -> PrettyJson<'_> {
1105 PrettyJson { inner: self }
1108 /// If the Json value is an Object, returns the value associated with the provided key.
1109 /// Otherwise, returns None.
1110 pub fn find(&self, key: &str) -> Option<&Json> {
1112 Json::Object(ref map) => map.get(key),
1117 /// Attempts to get a nested Json Object for each key in `keys`.
1118 /// If any key is found not to exist, `find_path` will return `None`.
1119 /// Otherwise, it will return the Json value associated with the final key.
1120 pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json> {
1121 let mut target = self;
1123 target = target.find(*key)?;
1128 /// If the Json value is an Object, performs a depth-first search until
1129 /// a value associated with the provided key is found. If no value is found
1130 /// or the Json value is not an Object, returns `None`.
1131 pub fn search(&self, key: &str) -> Option<&Json> {
1133 Json::Object(ref map) => match map.get(key) {
1134 Some(json_value) => Some(json_value),
1136 for v in map.values() {
1137 match v.search(key) {
1138 x if x.is_some() => return x,
1149 /// Returns `true` if the Json value is an `Object`.
1150 pub fn is_object(&self) -> bool {
1151 self.as_object().is_some()
1154 /// If the Json value is an `Object`, returns the associated `BTreeMap`;
1155 /// returns `None` otherwise.
1156 pub fn as_object(&self) -> Option<&Object> {
1158 Json::Object(ref map) => Some(map),
1163 /// Returns `true` if the Json value is an `Array`.
1164 pub fn is_array(&self) -> bool {
1165 self.as_array().is_some()
1168 /// If the Json value is an `Array`, returns the associated vector;
1169 /// returns `None` otherwise.
1170 pub fn as_array(&self) -> Option<&Array> {
1172 Json::Array(ref array) => Some(&*array),
1177 /// Returns `true` if the Json value is a `String`.
1178 pub fn is_string(&self) -> bool {
1179 self.as_string().is_some()
1182 /// If the Json value is a `String`, returns the associated `str`;
1183 /// returns `None` otherwise.
1184 pub fn as_string(&self) -> Option<&str> {
1186 Json::String(ref s) => Some(&s[..]),
1191 /// Returns `true` if the Json value is a `Number`.
1192 pub fn is_number(&self) -> bool {
1193 matches!(*self, Json::I64(_) | Json::U64(_) | Json::F64(_))
1196 /// Returns `true` if the Json value is a `i64`.
1197 pub fn is_i64(&self) -> bool {
1198 matches!(*self, Json::I64(_))
1201 /// Returns `true` if the Json value is a `u64`.
1202 pub fn is_u64(&self) -> bool {
1203 matches!(*self, Json::U64(_))
1206 /// Returns `true` if the Json value is a `f64`.
1207 pub fn is_f64(&self) -> bool {
1208 matches!(*self, Json::F64(_))
1211 /// If the Json value is a number, returns or cast it to a `i64`;
1212 /// returns `None` otherwise.
1213 pub fn as_i64(&self) -> Option<i64> {
1215 Json::I64(n) => Some(n),
1216 Json::U64(n) => Some(n as i64),
1221 /// If the Json value is a number, returns or cast it to a `u64`;
1222 /// returns `None` otherwise.
1223 pub fn as_u64(&self) -> Option<u64> {
1225 Json::I64(n) => Some(n as u64),
1226 Json::U64(n) => Some(n),
1231 /// If the Json value is a number, returns or cast it to a `f64`;
1232 /// returns `None` otherwise.
1233 pub fn as_f64(&self) -> Option<f64> {
1235 Json::I64(n) => Some(n as f64),
1236 Json::U64(n) => Some(n as f64),
1237 Json::F64(n) => Some(n),
1242 /// Returns `true` if the Json value is a `Boolean`.
1243 pub fn is_boolean(&self) -> bool {
1244 self.as_boolean().is_some()
1247 /// If the Json value is a `Boolean`, returns the associated `bool`;
1248 /// returns `None` otherwise.
1249 pub fn as_boolean(&self) -> Option<bool> {
1251 Json::Boolean(b) => Some(b),
1256 /// Returns `true` if the Json value is a `Null`.
1257 pub fn is_null(&self) -> bool {
1258 self.as_null().is_some()
1261 /// If the Json value is a `Null`, returns `()`;
1262 /// returns `None` otherwise.
1263 pub fn as_null(&self) -> Option<()> {
1265 Json::Null => Some(()),
1271 impl<'a> Index<&'a str> for Json {
1274 fn index(&self, idx: &'a str) -> &Json {
1275 self.find(idx).unwrap()
1279 impl Index<usize> for Json {
1282 fn index(&self, idx: usize) -> &Json {
1284 Json::Array(ref v) => &v[idx],
1285 _ => panic!("can only index Json with usize if it is an array"),
1290 /// The output of the streaming parser.
1291 #[derive(PartialEq, Clone, Debug)]
1292 pub enum JsonEvent {
1301 StringValue(string::String),
1306 #[derive(PartialEq, Debug)]
1308 // Parse a value in an array, true means first element.
1310 // Parse ',' or ']' after an element in an array.
1312 // Parse a key:value in an object, true means first element.
1314 // Parse ',' or ']' after an element in an object.
1318 // Expecting the stream to end.
1320 // Parsing can't continue.
1324 /// A Stack represents the current position of the parser in the logical
1325 /// structure of the JSON stream.
1327 /// An example is `foo.bar[3].x`.
1330 stack: Vec<InternalStackElement>,
1331 str_buffer: Vec<u8>,
1334 /// StackElements compose a Stack.
1336 /// As an example, `StackElement::Key("foo")`, `StackElement::Key("bar")`,
1337 /// `StackElement::Index(3)`, and `StackElement::Key("x")` are the
1338 /// StackElements composing the stack that represents `foo.bar[3].x`.
1339 #[derive(PartialEq, Clone, Debug)]
1340 pub enum StackElement<'l> {
1345 // Internally, Key elements are stored as indices in a buffer to avoid
1346 // allocating a string for every member of an object.
1347 #[derive(PartialEq, Clone, Debug)]
1348 enum InternalStackElement {
1350 InternalKey(u16, u16), // start, size
1354 pub fn new() -> Stack {
1358 /// Returns The number of elements in the Stack.
1359 pub fn len(&self) -> usize {
1363 /// Returns `true` if the stack is empty.
1364 pub fn is_empty(&self) -> bool {
1365 self.stack.is_empty()
1368 /// Provides access to the StackElement at a given index.
1369 /// lower indices are at the bottom of the stack while higher indices are
1371 pub fn get(&self, idx: usize) -> StackElement<'_> {
1372 match self.stack[idx] {
1373 InternalIndex(i) => StackElement::Index(i),
1374 InternalKey(start, size) => StackElement::Key(
1375 str::from_utf8(&self.str_buffer[start as usize..start as usize + size as usize])
1381 /// Compares this stack with an array of StackElement<'_>s.
1382 pub fn is_equal_to(&self, rhs: &[StackElement<'_>]) -> bool {
1383 if self.stack.len() != rhs.len() {
1386 for (i, r) in rhs.iter().enumerate() {
1387 if self.get(i) != *r {
1394 /// Returns `true` if the bottom-most elements of this stack are the same as
1395 /// the ones passed as parameter.
1396 pub fn starts_with(&self, rhs: &[StackElement<'_>]) -> bool {
1397 if self.stack.len() < rhs.len() {
1400 for (i, r) in rhs.iter().enumerate() {
1401 if self.get(i) != *r {
1408 /// Returns `true` if the top-most elements of this stack are the same as
1409 /// the ones passed as parameter.
1410 pub fn ends_with(&self, rhs: &[StackElement<'_>]) -> bool {
1411 if self.stack.len() < rhs.len() {
1414 let offset = self.stack.len() - rhs.len();
1415 for (i, r) in rhs.iter().enumerate() {
1416 if self.get(i + offset) != *r {
1423 /// Returns the top-most element (if any).
1424 pub fn top(&self) -> Option<StackElement<'_>> {
1425 match self.stack.last() {
1427 Some(&InternalIndex(i)) => Some(StackElement::Index(i)),
1428 Some(&InternalKey(start, size)) => Some(StackElement::Key(
1429 str::from_utf8(&self.str_buffer[start as usize..(start + size) as usize]).unwrap(),
1434 // Used by Parser to insert StackElement::Key elements at the top of the stack.
1435 fn push_key(&mut self, key: string::String) {
1436 self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
1437 self.str_buffer.extend(key.as_bytes());
1440 // Used by Parser to insert StackElement::Index elements at the top of the stack.
1441 fn push_index(&mut self, index: u32) {
1442 self.stack.push(InternalIndex(index));
1445 // Used by Parser to remove the top-most element of the stack.
1447 assert!(!self.is_empty());
1448 match *self.stack.last().unwrap() {
1449 InternalKey(_, sz) => {
1450 let new_size = self.str_buffer.len() - sz as usize;
1451 self.str_buffer.truncate(new_size);
1453 InternalIndex(_) => {}
1458 // Used by Parser to test whether the top-most element is an index.
1459 fn last_is_index(&self) -> bool {
1460 matches!(self.stack.last(), Some(InternalIndex(_)))
1463 // Used by Parser to increment the index of the top-most element.
1464 fn bump_index(&mut self) {
1465 let len = self.stack.len();
1466 let idx = match *self.stack.last().unwrap() {
1467 InternalIndex(i) => i + 1,
1472 self.stack[len - 1] = InternalIndex(idx);
1476 /// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
1477 /// an iterator of char.
1478 pub struct Parser<T> {
1483 // We maintain a stack representing where we are in the logical structure
1484 // of the JSON stream.
1486 // A state machine is kept to make it possible to interrupt and resume parsing.
1490 impl<T: Iterator<Item = char>> Iterator for Parser<T> {
1491 type Item = JsonEvent;
1493 fn next(&mut self) -> Option<JsonEvent> {
1494 if self.state == ParseFinished {
1498 if self.state == ParseBeforeFinish {
1499 self.parse_whitespace();
1500 // Make sure there is no trailing characters.
1502 self.state = ParseFinished;
1505 return Some(self.error_event(TrailingCharacters));
1513 impl<T: Iterator<Item = char>> Parser<T> {
1514 /// Creates the JSON parser.
1515 pub fn new(rdr: T) -> Parser<T> {
1516 let mut p = Parser {
1521 stack: Stack::new(),
1528 /// Provides access to the current position in the logical structure of the
1530 pub fn stack(&self) -> &Stack {
1534 fn eof(&self) -> bool {
1537 fn ch_or_null(&self) -> char {
1538 self.ch.unwrap_or('\x00')
1540 fn bump(&mut self) {
1541 self.ch = self.rdr.next();
1543 if self.ch_is('\n') {
1551 fn next_char(&mut self) -> Option<char> {
1555 fn ch_is(&self, c: char) -> bool {
1559 fn error<U>(&self, reason: ErrorCode) -> Result<U, ParserError> {
1560 Err(SyntaxError(reason, self.line, self.col))
1563 fn parse_whitespace(&mut self) {
1564 while self.ch_is(' ') || self.ch_is('\n') || self.ch_is('\t') || self.ch_is('\r') {
1569 fn parse_number(&mut self) -> JsonEvent {
1570 let neg = if self.ch_is('-') {
1577 let res = match self.parse_u64() {
1584 if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
1585 let mut res = res as f64;
1587 if self.ch_is('.') {
1588 res = match self.parse_decimal(res) {
1596 if self.ch_is('e') || self.ch_is('E') {
1597 res = match self.parse_exponent(res) {
1611 let res = (res as i64).wrapping_neg();
1613 // Make sure we didn't underflow.
1615 Error(SyntaxError(InvalidNumber, self.line, self.col))
1624 fn parse_u64(&mut self) -> Result<u64, ParserError> {
1625 let mut accum = 0u64;
1626 let last_accum = 0; // necessary to detect overflow.
1628 match self.ch_or_null() {
1632 // A leading '0' must be the only digit before the decimal point.
1633 if let '0'..='9' = self.ch_or_null() {
1634 return self.error(InvalidNumber);
1639 match self.ch_or_null() {
1641 accum = accum.wrapping_mul(10);
1642 accum = accum.wrapping_add((c as u64) - ('0' as u64));
1644 // Detect overflow by comparing to the last value.
1645 if accum <= last_accum {
1646 return self.error(InvalidNumber);
1655 _ => return self.error(InvalidNumber),
1661 fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1664 // Make sure a digit follows the decimal place.
1665 match self.ch_or_null() {
1667 _ => return self.error(InvalidNumber),
1672 match self.ch_or_null() {
1675 res += (((c as isize) - ('0' as isize)) as f64) * dec;
1685 fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1689 let mut neg_exp = false;
1691 if self.ch_is('+') {
1693 } else if self.ch_is('-') {
1698 // Make sure a digit follows the exponent place.
1699 match self.ch_or_null() {
1701 _ => return self.error(InvalidNumber),
1704 match self.ch_or_null() {
1707 exp += (c as usize) - ('0' as usize);
1715 let exp = 10_f64.powi(exp as i32);
1725 fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1728 while i < 4 && !self.eof() {
1730 n = match self.ch_or_null() {
1731 c @ '0'..='9' => n * 16 + ((c as u16) - ('0' as u16)),
1732 'a' | 'A' => n * 16 + 10,
1733 'b' | 'B' => n * 16 + 11,
1734 'c' | 'C' => n * 16 + 12,
1735 'd' | 'D' => n * 16 + 13,
1736 'e' | 'E' => n * 16 + 14,
1737 'f' | 'F' => n * 16 + 15,
1738 _ => return self.error(InvalidEscape),
1744 // Error out if we didn't parse 4 digits.
1746 return self.error(InvalidEscape);
1752 fn parse_str(&mut self) -> Result<string::String, ParserError> {
1753 let mut escape = false;
1754 let mut res = string::String::new();
1759 return self.error(EOFWhileParsingString);
1763 match self.ch_or_null() {
1764 '"' => res.push('"'),
1765 '\\' => res.push('\\'),
1766 '/' => res.push('/'),
1767 'b' => res.push('\x08'),
1768 'f' => res.push('\x0c'),
1769 'n' => res.push('\n'),
1770 'r' => res.push('\r'),
1771 't' => res.push('\t'),
1772 'u' => match self.decode_hex_escape()? {
1773 0xDC00..=0xDFFF => return self.error(LoneLeadingSurrogateInHexEscape),
1775 // Non-BMP characters are encoded as a sequence of
1776 // two hex escapes, representing UTF-16 surrogates.
1777 n1 @ 0xD800..=0xDBFF => {
1778 match (self.next_char(), self.next_char()) {
1779 (Some('\\'), Some('u')) => (),
1780 _ => return self.error(UnexpectedEndOfHexEscape),
1783 let n2 = self.decode_hex_escape()?;
1784 if !(0xDC00..=0xDFFF).contains(&n2) {
1785 return self.error(LoneLeadingSurrogateInHexEscape);
1788 (u32::from(n1 - 0xD800) << 10 | u32::from(n2 - 0xDC00)) + 0x1_0000;
1789 res.push(char::from_u32(c).unwrap());
1792 n => match char::from_u32(u32::from(n)) {
1793 Some(c) => res.push(c),
1794 None => return self.error(InvalidUnicodeCodePoint),
1797 _ => return self.error(InvalidEscape),
1800 } else if self.ch_is('\\') {
1808 Some(c) => res.push(c),
1809 None => unreachable!(),
1815 // Invoked at each iteration, consumes the stream until it has enough
1816 // information to return a JsonEvent.
1817 // Manages an internal state so that parsing can be interrupted and resumed.
1818 // Also keeps track of the position in the logical structure of the json
1819 // stream isize the form of a stack that can be queried by the user using the
1821 fn parse(&mut self) -> JsonEvent {
1823 // The only paths where the loop can spin a new iteration
1824 // are in the cases ParseArrayComma and ParseObjectComma if ','
1825 // is parsed. In these cases the state is set to (respectively)
1826 // ParseArray(false) and ParseObject(false), which always return,
1827 // so there is no risk of getting stuck in an infinite loop.
1828 // All other paths return before the end of the loop's iteration.
1829 self.parse_whitespace();
1833 return self.parse_start();
1835 ParseArray(first) => {
1836 return self.parse_array(first);
1838 ParseArrayComma => {
1839 if let Some(evt) = self.parse_array_comma_or_end() {
1843 ParseObject(first) => {
1844 return self.parse_object(first);
1846 ParseObjectComma => {
1848 if self.ch_is(',') {
1849 self.state = ParseObject(false);
1852 return self.parse_object_end();
1856 return self.error_event(InvalidSyntax);
1862 fn parse_start(&mut self) -> JsonEvent {
1863 let val = self.parse_value();
1864 self.state = match val {
1865 Error(_) => ParseFinished,
1866 ArrayStart => ParseArray(true),
1867 ObjectStart => ParseObject(true),
1868 _ => ParseBeforeFinish,
1873 fn parse_array(&mut self, first: bool) -> JsonEvent {
1874 if self.ch_is(']') {
1876 self.error_event(InvalidSyntax)
1878 self.state = if self.stack.is_empty() {
1880 } else if self.stack.last_is_index() {
1890 self.stack.push_index(0);
1892 let val = self.parse_value();
1893 self.state = match val {
1894 Error(_) => ParseFinished,
1895 ArrayStart => ParseArray(true),
1896 ObjectStart => ParseObject(true),
1897 _ => ParseArrayComma,
1903 fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
1904 if self.ch_is(',') {
1905 self.stack.bump_index();
1906 self.state = ParseArray(false);
1909 } else if self.ch_is(']') {
1911 self.state = if self.stack.is_empty() {
1913 } else if self.stack.last_is_index() {
1920 } else if self.eof() {
1921 Some(self.error_event(EOFWhileParsingArray))
1923 Some(self.error_event(InvalidSyntax))
1927 fn parse_object(&mut self, first: bool) -> JsonEvent {
1928 if self.ch_is('}') {
1930 if self.stack.is_empty() {
1931 return self.error_event(TrailingComma);
1936 self.state = if self.stack.is_empty() {
1938 } else if self.stack.last_is_index() {
1947 return self.error_event(EOFWhileParsingObject);
1949 if !self.ch_is('"') {
1950 return self.error_event(KeyMustBeAString);
1952 let s = match self.parse_str() {
1955 self.state = ParseFinished;
1959 self.parse_whitespace();
1961 return self.error_event(EOFWhileParsingObject);
1962 } else if self.ch_or_null() != ':' {
1963 return self.error_event(ExpectedColon);
1965 self.stack.push_key(s);
1967 self.parse_whitespace();
1969 let val = self.parse_value();
1971 self.state = match val {
1972 Error(_) => ParseFinished,
1973 ArrayStart => ParseArray(true),
1974 ObjectStart => ParseObject(true),
1975 _ => ParseObjectComma,
1980 fn parse_object_end(&mut self) -> JsonEvent {
1981 if self.ch_is('}') {
1982 self.state = if self.stack.is_empty() {
1984 } else if self.stack.last_is_index() {
1991 } else if self.eof() {
1992 self.error_event(EOFWhileParsingObject)
1994 self.error_event(InvalidSyntax)
1998 fn parse_value(&mut self) -> JsonEvent {
2000 return self.error_event(EOFWhileParsingValue);
2002 match self.ch_or_null() {
2003 'n' => self.parse_ident("ull", NullValue),
2004 't' => self.parse_ident("rue", BooleanValue(true)),
2005 'f' => self.parse_ident("alse", BooleanValue(false)),
2006 '0'..='9' | '-' => self.parse_number(),
2007 '"' => match self.parse_str() {
2008 Ok(s) => StringValue(s),
2019 _ => self.error_event(InvalidSyntax),
2023 fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
2024 if ident.chars().all(|c| Some(c) == self.next_char()) {
2028 Error(SyntaxError(InvalidSyntax, self.line, self.col))
2032 fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
2033 self.state = ParseFinished;
2034 Error(SyntaxError(reason, self.line, self.col))
2038 /// A Builder consumes a json::Parser to create a generic Json structure.
2039 pub struct Builder<T> {
2041 token: Option<JsonEvent>,
2044 impl<T: Iterator<Item = char>> Builder<T> {
2045 /// Creates a JSON Builder.
2046 pub fn new(src: T) -> Builder<T> {
2047 Builder { parser: Parser::new(src), token: None }
2050 // Decode a Json value from a Parser.
2051 pub fn build(&mut self) -> Result<Json, BuilderError> {
2053 let result = self.build_value();
2057 Some(Error(ref e)) => {
2058 return Err(e.clone());
2061 panic!("unexpected token {:?}", tok.clone());
2067 fn bump(&mut self) {
2068 self.token = self.parser.next();
2071 fn build_value(&mut self) -> Result<Json, BuilderError> {
2073 Some(NullValue) => Ok(Json::Null),
2074 Some(I64Value(n)) => Ok(Json::I64(n)),
2075 Some(U64Value(n)) => Ok(Json::U64(n)),
2076 Some(F64Value(n)) => Ok(Json::F64(n)),
2077 Some(BooleanValue(b)) => Ok(Json::Boolean(b)),
2078 Some(StringValue(ref mut s)) => {
2079 let mut temp = string::String::new();
2081 Ok(Json::String(temp))
2083 Some(Error(ref e)) => Err(e.clone()),
2084 Some(ArrayStart) => self.build_array(),
2085 Some(ObjectStart) => self.build_object(),
2086 Some(ObjectEnd) => self.parser.error(InvalidSyntax),
2087 Some(ArrayEnd) => self.parser.error(InvalidSyntax),
2088 None => self.parser.error(EOFWhileParsingValue),
2092 fn build_array(&mut self) -> Result<Json, BuilderError> {
2094 let mut values = Vec::new();
2097 if self.token == Some(ArrayEnd) {
2098 return Ok(Json::Array(values.into_iter().collect()));
2100 match self.build_value() {
2101 Ok(v) => values.push(v),
2102 Err(e) => return Err(e),
2108 fn build_object(&mut self) -> Result<Json, BuilderError> {
2111 let mut values = BTreeMap::new();
2115 Some(ObjectEnd) => {
2116 return Ok(Json::Object(values));
2118 Some(Error(ref e)) => {
2119 return Err(e.clone());
2126 let key = match self.parser.stack().top() {
2127 Some(StackElement::Key(k)) => k.to_owned(),
2129 panic!("invalid state");
2132 match self.build_value() {
2134 values.insert(key, value);
2142 self.parser.error(EOFWhileParsingObject)
2146 /// Decodes a json value from an `&mut io::Read`
2147 pub fn from_reader(rdr: &mut dyn Read) -> Result<Json, BuilderError> {
2148 let mut contents = Vec::new();
2149 match rdr.read_to_end(&mut contents) {
2151 Err(e) => return Err(io_error_to_error(e)),
2153 let s = match str::from_utf8(&contents).ok() {
2155 _ => return Err(SyntaxError(NotUtf8, 0, 0)),
2157 let mut builder = Builder::new(s.chars());
2161 /// Decodes a json value from a string
2162 pub fn from_str(s: &str) -> Result<Json, BuilderError> {
2163 let mut builder = Builder::new(s.chars());
2167 /// A structure to decode JSON to values in rust.
2168 pub struct Decoder {
2173 /// Creates a new decoder instance for decoding the specified JSON value.
2174 pub fn new(json: Json) -> Decoder {
2175 Decoder { stack: vec![json] }
2178 fn pop(&mut self) -> Json {
2179 self.stack.pop().unwrap()
2183 macro_rules! expect {
2184 ($e:expr, Null) => {{
2186 Json::Null => Ok(()),
2187 other => Err(ExpectedError("Null".to_owned(), other.to_string())),
2190 ($e:expr, $t:ident) => {{
2192 Json::$t(v) => Ok(v),
2193 other => Err(ExpectedError(stringify!($t).to_owned(), other.to_string())),
2198 macro_rules! read_primitive {
2199 ($name:ident, $ty:ty) => {
2200 fn $name(&mut self) -> DecodeResult<$ty> {
2202 Json::I64(f) => Ok(f as $ty),
2203 Json::U64(f) => Ok(f as $ty),
2204 Json::F64(f) => Err(ExpectedError("Integer".to_owned(), f.to_string())),
2205 // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
2206 // is going to have a string here, as per JSON spec.
2207 Json::String(s) => match s.parse().ok() {
2209 None => Err(ExpectedError("Number".to_owned(), s)),
2211 value => Err(ExpectedError("Number".to_owned(), value.to_string())),
2217 impl crate::Decoder for Decoder {
2218 type Error = DecoderError;
2220 fn read_nil(&mut self) -> DecodeResult<()> {
2221 expect!(self.pop(), Null)
2224 read_primitive! { read_usize, usize }
2225 read_primitive! { read_u8, u8 }
2226 read_primitive! { read_u16, u16 }
2227 read_primitive! { read_u32, u32 }
2228 read_primitive! { read_u64, u64 }
2229 read_primitive! { read_u128, u128 }
2230 read_primitive! { read_isize, isize }
2231 read_primitive! { read_i8, i8 }
2232 read_primitive! { read_i16, i16 }
2233 read_primitive! { read_i32, i32 }
2234 read_primitive! { read_i64, i64 }
2235 read_primitive! { read_i128, i128 }
2237 fn read_f32(&mut self) -> DecodeResult<f32> {
2238 self.read_f64().map(|x| x as f32)
2241 fn read_f64(&mut self) -> DecodeResult<f64> {
2243 Json::I64(f) => Ok(f as f64),
2244 Json::U64(f) => Ok(f as f64),
2245 Json::F64(f) => Ok(f),
2246 Json::String(s) => {
2247 // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
2248 // is going to have a string here, as per JSON spec.
2249 match s.parse().ok() {
2251 None => Err(ExpectedError("Number".to_owned(), s)),
2254 Json::Null => Ok(f64::NAN),
2255 value => Err(ExpectedError("Number".to_owned(), value.to_string())),
2259 fn read_bool(&mut self) -> DecodeResult<bool> {
2260 expect!(self.pop(), Boolean)
2263 fn read_char(&mut self) -> DecodeResult<char> {
2264 let s = self.read_str()?;
2266 let mut it = s.chars();
2267 if let (Some(c), None) = (it.next(), it.next()) {
2268 // exactly one character
2272 Err(ExpectedError("single character string".to_owned(), s.to_string()))
2275 fn read_str(&mut self) -> DecodeResult<Cow<'_, str>> {
2276 expect!(self.pop(), String).map(Cow::Owned)
2279 fn read_raw_bytes_into(&mut self, s: &mut [u8]) -> Result<(), Self::Error> {
2280 for c in s.iter_mut() {
2281 *c = self.read_u8()?;
2286 fn read_enum<T, F>(&mut self, f: F) -> DecodeResult<T>
2288 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2293 fn read_enum_variant<T, F>(&mut self, names: &[&str], mut f: F) -> DecodeResult<T>
2295 F: FnMut(&mut Decoder, usize) -> DecodeResult<T>,
2297 let name = match self.pop() {
2298 Json::String(s) => s,
2299 Json::Object(mut o) => {
2300 let n = match o.remove(&"variant".to_owned()) {
2301 Some(Json::String(s)) => s,
2302 Some(val) => return Err(ExpectedError("String".to_owned(), val.to_string())),
2303 None => return Err(MissingFieldError("variant".to_owned())),
2305 match o.remove(&"fields".to_string()) {
2306 Some(Json::Array(l)) => {
2307 self.stack.extend(l.into_iter().rev());
2309 Some(val) => return Err(ExpectedError("Array".to_owned(), val.to_string())),
2310 None => return Err(MissingFieldError("fields".to_owned())),
2314 json => return Err(ExpectedError("String or Object".to_owned(), json.to_string())),
2316 let idx = match names.iter().position(|n| *n == &name[..]) {
2318 None => return Err(UnknownVariantError(name)),
2323 fn read_enum_variant_arg<T, F>(&mut self, f: F) -> DecodeResult<T>
2325 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2330 fn read_struct<T, F>(&mut self, f: F) -> DecodeResult<T>
2332 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2334 let value = f(self)?;
2339 fn read_struct_field<T, F>(&mut self, name: &str, f: F) -> DecodeResult<T>
2341 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2343 let mut obj = expect!(self.pop(), Object)?;
2345 let value = match obj.remove(&name.to_string()) {
2347 // Add a Null and try to parse it as an Option<_>
2348 // to get None as a default value.
2349 self.stack.push(Json::Null);
2352 Err(_) => return Err(MissingFieldError(name.to_string())),
2356 self.stack.push(json);
2360 self.stack.push(Json::Object(obj));
2364 fn read_tuple<T, F>(&mut self, tuple_len: usize, f: F) -> DecodeResult<T>
2366 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2368 self.read_seq(move |d, len| {
2369 if len == tuple_len {
2372 Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)))
2377 fn read_tuple_arg<T, F>(&mut self, f: F) -> DecodeResult<T>
2379 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2381 self.read_seq_elt(f)
2384 fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T>
2386 F: FnMut(&mut Decoder, bool) -> DecodeResult<T>,
2389 Json::Null => f(self, false),
2391 self.stack.push(value);
2397 fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T>
2399 F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
2401 let array = expect!(self.pop(), Array)?;
2402 let len = array.len();
2403 self.stack.extend(array.into_iter().rev());
2407 fn read_seq_elt<T, F>(&mut self, f: F) -> DecodeResult<T>
2409 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2414 fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T>
2416 F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
2418 let obj = expect!(self.pop(), Object)?;
2419 let len = obj.len();
2420 for (key, value) in obj {
2421 self.stack.push(value);
2422 self.stack.push(Json::String(key));
2427 fn read_map_elt_key<T, F>(&mut self, f: F) -> DecodeResult<T>
2429 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2434 fn read_map_elt_val<T, F>(&mut self, f: F) -> DecodeResult<T>
2436 F: FnOnce(&mut Decoder) -> DecodeResult<T>,
2441 fn error(&mut self, err: &str) -> DecoderError {
2442 ApplicationError(err.to_string())
2446 /// A trait for converting values to JSON
2448 /// Converts the value of `self` to an instance of JSON
2449 fn to_json(&self) -> Json;
2452 macro_rules! to_json_impl_i64 {
2454 $(impl ToJson for $t {
2455 fn to_json(&self) -> Json {
2456 Json::I64(*self as i64)
2462 to_json_impl_i64! { isize, i8, i16, i32, i64 }
2464 macro_rules! to_json_impl_u64 {
2466 $(impl ToJson for $t {
2467 fn to_json(&self) -> Json {
2468 Json::U64(*self as u64)
2474 to_json_impl_u64! { usize, u8, u16, u32, u64 }
2476 impl ToJson for Json {
2477 fn to_json(&self) -> Json {
2482 impl ToJson for f32 {
2483 fn to_json(&self) -> Json {
2484 f64::from(*self).to_json()
2488 impl ToJson for f64 {
2489 fn to_json(&self) -> Json {
2490 match self.classify() {
2491 Fp::Nan | Fp::Infinite => Json::Null,
2492 _ => Json::F64(*self),
2497 impl ToJson for () {
2498 fn to_json(&self) -> Json {
2503 impl ToJson for bool {
2504 fn to_json(&self) -> Json {
2505 Json::Boolean(*self)
2509 impl ToJson for str {
2510 fn to_json(&self) -> Json {
2511 Json::String(self.to_string())
2515 impl ToJson for string::String {
2516 fn to_json(&self) -> Json {
2517 Json::String((*self).clone())
2521 macro_rules! tuple_impl {
2522 // use variables to indicate the arity of the tuple
2523 ($($tyvar:ident),* ) => {
2524 // the trailing commas are for the 1 tuple
2526 $( $tyvar : ToJson ),*
2527 > ToJson for ( $( $tyvar ),* , ) {
2530 #[allow(non_snake_case)]
2531 fn to_json(&self) -> Json {
2533 ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
2542 tuple_impl! {A, B, C}
2543 tuple_impl! {A, B, C, D}
2544 tuple_impl! {A, B, C, D, E}
2545 tuple_impl! {A, B, C, D, E, F}
2546 tuple_impl! {A, B, C, D, E, F, G}
2547 tuple_impl! {A, B, C, D, E, F, G, H}
2548 tuple_impl! {A, B, C, D, E, F, G, H, I}
2549 tuple_impl! {A, B, C, D, E, F, G, H, I, J}
2550 tuple_impl! {A, B, C, D, E, F, G, H, I, J, K}
2551 tuple_impl! {A, B, C, D, E, F, G, H, I, J, K, L}
2553 impl<A: ToJson> ToJson for [A] {
2554 fn to_json(&self) -> Json {
2555 Json::Array(self.iter().map(|elt| elt.to_json()).collect())
2559 impl<A: ToJson> ToJson for Vec<A> {
2560 fn to_json(&self) -> Json {
2561 Json::Array(self.iter().map(|elt| elt.to_json()).collect())
2565 impl<T: ToString, A: ToJson> ToJson for BTreeMap<T, A> {
2566 fn to_json(&self) -> Json {
2567 let mut d = BTreeMap::new();
2568 for (key, value) in self {
2569 d.insert(key.to_string(), value.to_json());
2575 impl<A: ToJson> ToJson for HashMap<string::String, A> {
2576 fn to_json(&self) -> Json {
2577 let mut d = BTreeMap::new();
2578 for (key, value) in self {
2579 d.insert((*key).clone(), value.to_json());
2585 impl<A: ToJson> ToJson for Option<A> {
2586 fn to_json(&self) -> Json {
2589 Some(ref value) => value.to_json(),
2594 struct FormatShim<'a, 'b> {
2595 inner: &'a mut fmt::Formatter<'b>,
2598 impl<'a, 'b> fmt::Write for FormatShim<'a, 'b> {
2599 fn write_str(&mut self, s: &str) -> fmt::Result {
2600 match self.inner.write_str(s) {
2602 Err(_) => Err(fmt::Error),
2607 impl fmt::Display for Json {
2608 /// Encodes a json value into a string
2609 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2610 let mut shim = FormatShim { inner: f };
2611 let mut encoder = Encoder::new(&mut shim);
2612 match self.encode(&mut encoder) {
2614 Err(_) => Err(fmt::Error),
2619 impl<'a> fmt::Display for PrettyJson<'a> {
2620 /// Encodes a json value into a string
2621 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2622 let mut shim = FormatShim { inner: f };
2623 let mut encoder = PrettyEncoder::new(&mut shim);
2624 match self.inner.encode(&mut encoder) {
2626 Err(_) => Err(fmt::Error),
2631 impl<'a, T: for<'r> Encodable<Encoder<'r>>> fmt::Display for AsJson<'a, T> {
2632 /// Encodes a json value into a string
2633 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2634 let mut shim = FormatShim { inner: f };
2635 let mut encoder = Encoder::new(&mut shim);
2636 match self.inner.encode(&mut encoder) {
2638 Err(_) => Err(fmt::Error),
2643 impl<'a, T> AsPrettyJson<'a, T> {
2644 /// Sets the indentation level for the emitted JSON
2645 pub fn indent(mut self, indent: usize) -> AsPrettyJson<'a, T> {
2646 self.indent = Some(indent);
2651 impl<'a, T: for<'x> Encodable<PrettyEncoder<'x>>> fmt::Display for AsPrettyJson<'a, T> {
2652 /// Encodes a json value into a string
2653 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2654 let mut shim = FormatShim { inner: f };
2655 let mut encoder = PrettyEncoder::new(&mut shim);
2656 if let Some(n) = self.indent {
2657 encoder.set_indent(n);
2659 match self.inner.encode(&mut encoder) {
2661 Err(_) => Err(fmt::Error),
2666 impl FromStr for Json {
2667 type Err = BuilderError;
2668 fn from_str(s: &str) -> Result<Json, BuilderError> {