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[..]);
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);
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),
270 panic!("json decode error: {:?}", $e);
274 #[derive(Copy, Clone, Debug)]
275 pub enum EncoderError {
276 FmtError(fmt::Error),
280 /// Returns a readable error string for a given error code.
281 pub fn error_str(error: ErrorCode) -> &'static str {
283 InvalidSyntax => "invalid syntax",
284 InvalidNumber => "invalid number",
285 EOFWhileParsingObject => "EOF While parsing object",
286 EOFWhileParsingArray => "EOF While parsing array",
287 EOFWhileParsingValue => "EOF While parsing value",
288 EOFWhileParsingString => "EOF While parsing string",
289 KeyMustBeAString => "key must be a string",
290 ExpectedColon => "expected `:`",
291 TrailingCharacters => "trailing characters",
292 TrailingComma => "trailing comma",
293 InvalidEscape => "invalid escape",
294 UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)",
295 NotFourDigit => "invalid \\u{ esc}ape (not four digits)",
296 NotUtf8 => "contents not utf-8",
297 InvalidUnicodeCodePoint => "invalid Unicode code point",
298 LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
299 UnexpectedEndOfHexEscape => "unexpected end of hex escape",
303 /// Shortcut function to decode a JSON `&str` into an object
304 pub fn decode<T: crate::Decodable<Decoder>>(s: &str) -> T {
305 let json = match from_str(s) {
307 Err(e) => bad!(ParseError(e)),
310 let mut decoder = Decoder::new(json);
311 crate::Decodable::decode(&mut decoder)
314 /// Shortcut function to encode a `T` into a JSON `String`
315 pub fn encode<T: for<'r> crate::Encodable<Encoder<'r>>>(
317 ) -> Result<string::String, EncoderError> {
318 let mut s = String::new();
320 let mut encoder = Encoder::new(&mut s);
321 object.encode(&mut encoder)?;
326 impl fmt::Display for ErrorCode {
327 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328 error_str(*self).fmt(f)
332 fn io_error_to_error(io: io::Error) -> ParserError {
333 IoError(io.kind(), io.to_string())
336 impl fmt::Display for ParserError {
337 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338 // FIXME this should be a nicer error
339 fmt::Debug::fmt(self, f)
343 impl fmt::Display for EncoderError {
344 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
345 // FIXME this should be a nicer error
346 fmt::Debug::fmt(self, f)
350 impl std::error::Error for EncoderError {}
352 impl From<fmt::Error> for EncoderError {
353 /// Converts a [`fmt::Error`] into `EncoderError`
355 /// This conversion does not allocate memory.
356 fn from(err: fmt::Error) -> EncoderError {
357 EncoderError::FmtError(err)
361 pub type EncodeResult = Result<(), EncoderError>;
362 pub type DecodeResult<T> = Result<T, DecoderError>;
364 fn escape_str(wr: &mut dyn fmt::Write, v: &str) -> EncodeResult {
369 for (i, byte) in v.bytes().enumerate() {
370 let escaped = match byte {
373 b'\x00' => "\\u0000",
374 b'\x01' => "\\u0001",
375 b'\x02' => "\\u0002",
376 b'\x03' => "\\u0003",
377 b'\x04' => "\\u0004",
378 b'\x05' => "\\u0005",
379 b'\x06' => "\\u0006",
380 b'\x07' => "\\u0007",
384 b'\x0b' => "\\u000b",
387 b'\x0e' => "\\u000e",
388 b'\x0f' => "\\u000f",
389 b'\x10' => "\\u0010",
390 b'\x11' => "\\u0011",
391 b'\x12' => "\\u0012",
392 b'\x13' => "\\u0013",
393 b'\x14' => "\\u0014",
394 b'\x15' => "\\u0015",
395 b'\x16' => "\\u0016",
396 b'\x17' => "\\u0017",
397 b'\x18' => "\\u0018",
398 b'\x19' => "\\u0019",
399 b'\x1a' => "\\u001a",
400 b'\x1b' => "\\u001b",
401 b'\x1c' => "\\u001c",
402 b'\x1d' => "\\u001d",
403 b'\x1e' => "\\u001e",
404 b'\x1f' => "\\u001f",
405 b'\x7f' => "\\u007f",
412 wr.write_str(&v[start..i])?;
415 wr.write_str(escaped)?;
420 if start != v.len() {
421 wr.write_str(&v[start..])?;
428 fn escape_char(writer: &mut dyn fmt::Write, v: char) -> EncodeResult {
429 escape_str(writer, v.encode_utf8(&mut [0; 4]))
432 fn spaces(wr: &mut dyn fmt::Write, mut n: usize) -> EncodeResult {
433 const BUF: &str = " ";
435 while n >= BUF.len() {
441 wr.write_str(&BUF[..n])?;
446 fn fmt_number_or_null(v: f64) -> string::String {
448 Fp::Nan | Fp::Infinite => string::String::from("null"),
449 _ if v.fract() != 0f64 => v.to_string(),
450 _ => v.to_string() + ".0",
454 /// A structure for implementing serialization to JSON.
455 pub struct Encoder<'a> {
456 writer: &'a mut (dyn fmt::Write + 'a),
457 is_emitting_map_key: bool,
460 impl<'a> Encoder<'a> {
461 /// Creates a new JSON encoder whose output will be written to the writer
463 pub fn new(writer: &'a mut dyn fmt::Write) -> Encoder<'a> {
464 Encoder { writer, is_emitting_map_key: false }
468 macro_rules! emit_enquoted_if_mapkey {
469 ($enc:ident,$e:expr) => {{
470 if $enc.is_emitting_map_key {
471 write!($enc.writer, "\"{}\"", $e)?;
473 write!($enc.writer, "{}", $e)?;
479 impl<'a> crate::Encoder for Encoder<'a> {
480 type Error = EncoderError;
482 fn emit_unit(&mut self) -> EncodeResult {
483 if self.is_emitting_map_key {
484 return Err(EncoderError::BadHashmapKey);
486 write!(self.writer, "null")?;
490 fn emit_usize(&mut self, v: usize) -> EncodeResult {
491 emit_enquoted_if_mapkey!(self, v)
493 fn emit_u128(&mut self, v: u128) -> EncodeResult {
494 emit_enquoted_if_mapkey!(self, v)
496 fn emit_u64(&mut self, v: u64) -> EncodeResult {
497 emit_enquoted_if_mapkey!(self, v)
499 fn emit_u32(&mut self, v: u32) -> EncodeResult {
500 emit_enquoted_if_mapkey!(self, v)
502 fn emit_u16(&mut self, v: u16) -> EncodeResult {
503 emit_enquoted_if_mapkey!(self, v)
505 fn emit_u8(&mut self, v: u8) -> EncodeResult {
506 emit_enquoted_if_mapkey!(self, v)
509 fn emit_isize(&mut self, v: isize) -> EncodeResult {
510 emit_enquoted_if_mapkey!(self, v)
512 fn emit_i128(&mut self, v: i128) -> EncodeResult {
513 emit_enquoted_if_mapkey!(self, v)
515 fn emit_i64(&mut self, v: i64) -> EncodeResult {
516 emit_enquoted_if_mapkey!(self, v)
518 fn emit_i32(&mut self, v: i32) -> EncodeResult {
519 emit_enquoted_if_mapkey!(self, v)
521 fn emit_i16(&mut self, v: i16) -> EncodeResult {
522 emit_enquoted_if_mapkey!(self, v)
524 fn emit_i8(&mut self, v: i8) -> EncodeResult {
525 emit_enquoted_if_mapkey!(self, v)
528 fn emit_bool(&mut self, v: bool) -> EncodeResult {
529 if self.is_emitting_map_key {
530 return Err(EncoderError::BadHashmapKey);
533 write!(self.writer, "true")?;
535 write!(self.writer, "false")?;
540 fn emit_f64(&mut self, v: f64) -> EncodeResult {
541 emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
543 fn emit_f32(&mut self, v: f32) -> EncodeResult {
544 self.emit_f64(f64::from(v))
547 fn emit_char(&mut self, v: char) -> EncodeResult {
548 escape_char(self.writer, v)
550 fn emit_str(&mut self, v: &str) -> EncodeResult {
551 escape_str(self.writer, v)
553 fn emit_raw_bytes(&mut self, s: &[u8]) -> Result<(), Self::Error> {
560 fn emit_enum<F>(&mut self, f: F) -> EncodeResult
562 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
567 fn emit_enum_variant<F>(&mut self, name: &str, _id: usize, cnt: usize, f: F) -> EncodeResult
569 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
571 // enums are encoded as strings or objects
573 // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
575 escape_str(self.writer, name)
577 if self.is_emitting_map_key {
578 return Err(EncoderError::BadHashmapKey);
580 write!(self.writer, "{{\"variant\":")?;
581 escape_str(self.writer, name)?;
582 write!(self.writer, ",\"fields\":[")?;
584 write!(self.writer, "]}}")?;
589 fn emit_fieldless_enum_variant<const ID: usize>(
592 ) -> Result<(), Self::Error> {
593 escape_str(self.writer, name)
596 fn emit_enum_variant_arg<F>(&mut self, first: bool, f: F) -> EncodeResult
598 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
600 if self.is_emitting_map_key {
601 return Err(EncoderError::BadHashmapKey);
604 write!(self.writer, ",")?;
609 fn emit_struct<F>(&mut self, _: bool, f: F) -> EncodeResult
611 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
613 if self.is_emitting_map_key {
614 return Err(EncoderError::BadHashmapKey);
616 write!(self.writer, "{{")?;
618 write!(self.writer, "}}")?;
622 fn emit_struct_field<F>(&mut self, name: &str, first: bool, f: F) -> EncodeResult
624 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
626 if self.is_emitting_map_key {
627 return Err(EncoderError::BadHashmapKey);
630 write!(self.writer, ",")?;
632 escape_str(self.writer, name)?;
633 write!(self.writer, ":")?;
637 fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult
639 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
641 if self.is_emitting_map_key {
642 return Err(EncoderError::BadHashmapKey);
644 self.emit_seq(len, f)
646 fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
648 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
650 if self.is_emitting_map_key {
651 return Err(EncoderError::BadHashmapKey);
653 self.emit_seq_elt(idx, f)
656 fn emit_option<F>(&mut self, f: F) -> EncodeResult
658 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
660 if self.is_emitting_map_key {
661 return Err(EncoderError::BadHashmapKey);
665 fn emit_option_none(&mut self) -> EncodeResult {
666 if self.is_emitting_map_key {
667 return Err(EncoderError::BadHashmapKey);
671 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult
673 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
675 if self.is_emitting_map_key {
676 return Err(EncoderError::BadHashmapKey);
681 fn emit_seq<F>(&mut self, _len: usize, f: F) -> EncodeResult
683 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
685 if self.is_emitting_map_key {
686 return Err(EncoderError::BadHashmapKey);
688 write!(self.writer, "[")?;
690 write!(self.writer, "]")?;
694 fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult
696 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
698 if self.is_emitting_map_key {
699 return Err(EncoderError::BadHashmapKey);
702 write!(self.writer, ",")?;
707 fn emit_map<F>(&mut self, _len: usize, f: F) -> EncodeResult
709 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
711 if self.is_emitting_map_key {
712 return Err(EncoderError::BadHashmapKey);
714 write!(self.writer, "{{")?;
716 write!(self.writer, "}}")?;
720 fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult
722 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
724 if self.is_emitting_map_key {
725 return Err(EncoderError::BadHashmapKey);
728 write!(self.writer, ",")?
730 self.is_emitting_map_key = true;
732 self.is_emitting_map_key = false;
736 fn emit_map_elt_val<F>(&mut self, f: F) -> EncodeResult
738 F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
740 if self.is_emitting_map_key {
741 return Err(EncoderError::BadHashmapKey);
743 write!(self.writer, ":")?;
748 /// Another encoder for JSON, but prints out human-readable JSON instead of
750 pub struct PrettyEncoder<'a> {
751 writer: &'a mut (dyn fmt::Write + 'a),
754 is_emitting_map_key: bool,
757 impl<'a> PrettyEncoder<'a> {
758 /// Creates a new encoder whose output will be written to the specified writer
759 pub fn new(writer: &'a mut dyn fmt::Write) -> PrettyEncoder<'a> {
760 PrettyEncoder { writer, curr_indent: 0, indent: 2, is_emitting_map_key: false }
763 /// Sets the number of spaces to indent for each level.
764 /// This is safe to set during encoding.
765 pub fn set_indent(&mut self, indent: usize) {
766 // self.indent very well could be 0 so we need to use checked division.
767 let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
768 self.indent = indent;
769 self.curr_indent = level * self.indent;
773 impl<'a> crate::Encoder for PrettyEncoder<'a> {
774 type Error = EncoderError;
776 fn emit_unit(&mut self) -> EncodeResult {
777 if self.is_emitting_map_key {
778 return Err(EncoderError::BadHashmapKey);
780 write!(self.writer, "null")?;
784 fn emit_usize(&mut self, v: usize) -> EncodeResult {
785 emit_enquoted_if_mapkey!(self, v)
787 fn emit_u128(&mut self, v: u128) -> EncodeResult {
788 emit_enquoted_if_mapkey!(self, v)
790 fn emit_u64(&mut self, v: u64) -> EncodeResult {
791 emit_enquoted_if_mapkey!(self, v)
793 fn emit_u32(&mut self, v: u32) -> EncodeResult {
794 emit_enquoted_if_mapkey!(self, v)
796 fn emit_u16(&mut self, v: u16) -> EncodeResult {
797 emit_enquoted_if_mapkey!(self, v)
799 fn emit_u8(&mut self, v: u8) -> EncodeResult {
800 emit_enquoted_if_mapkey!(self, v)
803 fn emit_isize(&mut self, v: isize) -> EncodeResult {
804 emit_enquoted_if_mapkey!(self, v)
806 fn emit_i128(&mut self, v: i128) -> EncodeResult {
807 emit_enquoted_if_mapkey!(self, v)
809 fn emit_i64(&mut self, v: i64) -> EncodeResult {
810 emit_enquoted_if_mapkey!(self, v)
812 fn emit_i32(&mut self, v: i32) -> EncodeResult {
813 emit_enquoted_if_mapkey!(self, v)
815 fn emit_i16(&mut self, v: i16) -> EncodeResult {
816 emit_enquoted_if_mapkey!(self, v)
818 fn emit_i8(&mut self, v: i8) -> EncodeResult {
819 emit_enquoted_if_mapkey!(self, v)
822 fn emit_bool(&mut self, v: bool) -> EncodeResult {
823 if self.is_emitting_map_key {
824 return Err(EncoderError::BadHashmapKey);
827 write!(self.writer, "true")?;
829 write!(self.writer, "false")?;
834 fn emit_f64(&mut self, v: f64) -> EncodeResult {
835 emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
837 fn emit_f32(&mut self, v: f32) -> EncodeResult {
838 self.emit_f64(f64::from(v))
841 fn emit_char(&mut self, v: char) -> EncodeResult {
842 escape_char(self.writer, v)
844 fn emit_str(&mut self, v: &str) -> EncodeResult {
845 escape_str(self.writer, v)
847 fn emit_raw_bytes(&mut self, s: &[u8]) -> Result<(), Self::Error> {
854 fn emit_enum<F>(&mut self, f: F) -> EncodeResult
856 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
861 fn emit_enum_variant<F>(&mut self, name: &str, _id: usize, cnt: usize, f: F) -> EncodeResult
863 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
866 escape_str(self.writer, name)
868 if self.is_emitting_map_key {
869 return Err(EncoderError::BadHashmapKey);
871 writeln!(self.writer, "{{")?;
872 self.curr_indent += self.indent;
873 spaces(self.writer, self.curr_indent)?;
874 write!(self.writer, "\"variant\": ")?;
875 escape_str(self.writer, name)?;
876 writeln!(self.writer, ",")?;
877 spaces(self.writer, self.curr_indent)?;
878 writeln!(self.writer, "\"fields\": [")?;
879 self.curr_indent += self.indent;
881 self.curr_indent -= self.indent;
882 writeln!(self.writer)?;
883 spaces(self.writer, self.curr_indent)?;
884 self.curr_indent -= self.indent;
885 writeln!(self.writer, "]")?;
886 spaces(self.writer, self.curr_indent)?;
887 write!(self.writer, "}}")?;
892 fn emit_fieldless_enum_variant<const ID: usize>(
895 ) -> Result<(), Self::Error> {
896 escape_str(self.writer, name)
899 fn emit_enum_variant_arg<F>(&mut self, first: bool, f: F) -> EncodeResult
901 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
903 if self.is_emitting_map_key {
904 return Err(EncoderError::BadHashmapKey);
907 writeln!(self.writer, ",")?;
909 spaces(self.writer, self.curr_indent)?;
913 fn emit_struct<F>(&mut self, no_fields: bool, f: F) -> EncodeResult
915 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
917 if self.is_emitting_map_key {
918 return Err(EncoderError::BadHashmapKey);
921 write!(self.writer, "{{}}")?;
923 write!(self.writer, "{{")?;
924 self.curr_indent += self.indent;
926 self.curr_indent -= self.indent;
927 writeln!(self.writer)?;
928 spaces(self.writer, self.curr_indent)?;
929 write!(self.writer, "}}")?;
934 fn emit_struct_field<F>(&mut self, name: &str, first: bool, f: F) -> EncodeResult
936 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
938 if self.is_emitting_map_key {
939 return Err(EncoderError::BadHashmapKey);
942 writeln!(self.writer)?;
944 writeln!(self.writer, ",")?;
946 spaces(self.writer, self.curr_indent)?;
947 escape_str(self.writer, name)?;
948 write!(self.writer, ": ")?;
952 fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult
954 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
956 if self.is_emitting_map_key {
957 return Err(EncoderError::BadHashmapKey);
959 self.emit_seq(len, f)
961 fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
963 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
965 if self.is_emitting_map_key {
966 return Err(EncoderError::BadHashmapKey);
968 self.emit_seq_elt(idx, f)
971 fn emit_option<F>(&mut self, f: F) -> EncodeResult
973 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
975 if self.is_emitting_map_key {
976 return Err(EncoderError::BadHashmapKey);
980 fn emit_option_none(&mut self) -> EncodeResult {
981 if self.is_emitting_map_key {
982 return Err(EncoderError::BadHashmapKey);
986 fn emit_option_some<F>(&mut self, f: F) -> EncodeResult
988 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
990 if self.is_emitting_map_key {
991 return Err(EncoderError::BadHashmapKey);
996 fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodeResult
998 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1000 if self.is_emitting_map_key {
1001 return Err(EncoderError::BadHashmapKey);
1004 write!(self.writer, "[]")?;
1006 write!(self.writer, "[")?;
1007 self.curr_indent += self.indent;
1009 self.curr_indent -= self.indent;
1010 writeln!(self.writer)?;
1011 spaces(self.writer, self.curr_indent)?;
1012 write!(self.writer, "]")?;
1017 fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult
1019 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1021 if self.is_emitting_map_key {
1022 return Err(EncoderError::BadHashmapKey);
1025 writeln!(self.writer)?;
1027 writeln!(self.writer, ",")?;
1029 spaces(self.writer, self.curr_indent)?;
1033 fn emit_map<F>(&mut self, len: usize, f: F) -> EncodeResult
1035 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1037 if self.is_emitting_map_key {
1038 return Err(EncoderError::BadHashmapKey);
1041 write!(self.writer, "{{}}")?;
1043 write!(self.writer, "{{")?;
1044 self.curr_indent += self.indent;
1046 self.curr_indent -= self.indent;
1047 writeln!(self.writer)?;
1048 spaces(self.writer, self.curr_indent)?;
1049 write!(self.writer, "}}")?;
1054 fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult
1056 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1058 if self.is_emitting_map_key {
1059 return Err(EncoderError::BadHashmapKey);
1062 writeln!(self.writer)?;
1064 writeln!(self.writer, ",")?;
1066 spaces(self.writer, self.curr_indent)?;
1067 self.is_emitting_map_key = true;
1069 self.is_emitting_map_key = false;
1073 fn emit_map_elt_val<F>(&mut self, f: F) -> EncodeResult
1075 F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
1077 if self.is_emitting_map_key {
1078 return Err(EncoderError::BadHashmapKey);
1080 write!(self.writer, ": ")?;
1085 impl<E: crate::Encoder> Encodable<E> for Json {
1086 fn encode(&self, e: &mut E) -> Result<(), E::Error> {
1088 Json::I64(v) => v.encode(e),
1089 Json::U64(v) => v.encode(e),
1090 Json::F64(v) => v.encode(e),
1091 Json::String(ref v) => v.encode(e),
1092 Json::Boolean(v) => v.encode(e),
1093 Json::Array(ref v) => v.encode(e),
1094 Json::Object(ref v) => v.encode(e),
1095 Json::Null => e.emit_unit(),
1100 /// Creates an `AsJson` wrapper which can be used to print a value as JSON
1101 /// on-the-fly via `write!`
1102 pub fn as_json<T>(t: &T) -> AsJson<'_, T> {
1106 /// Creates an `AsPrettyJson` wrapper which can be used to print a value as JSON
1107 /// on-the-fly via `write!`
1108 pub fn as_pretty_json<T>(t: &T) -> AsPrettyJson<'_, T> {
1109 AsPrettyJson { inner: t, indent: None }
1113 /// Borrow this json object as a pretty object to generate a pretty
1114 /// representation for it via `Display`.
1115 pub fn pretty(&self) -> PrettyJson<'_> {
1116 PrettyJson { inner: self }
1119 /// If the Json value is an Object, returns the value associated with the provided key.
1120 /// Otherwise, returns None.
1121 pub fn find(&self, key: &str) -> Option<&Json> {
1123 Json::Object(ref map) => map.get(key),
1128 /// If the Json value is an Object, deletes the value associated with the
1129 /// provided key from the Object and returns it. Otherwise, returns None.
1130 pub fn remove_key(&mut self, key: &str) -> Option<Json> {
1132 Json::Object(ref mut map) => map.remove(key),
1137 /// Attempts to get a nested Json Object for each key in `keys`.
1138 /// If any key is found not to exist, `find_path` will return `None`.
1139 /// Otherwise, it will return the Json value associated with the final key.
1140 pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json> {
1141 let mut target = self;
1143 target = target.find(*key)?;
1148 /// If the Json value is an Object, performs a depth-first search until
1149 /// a value associated with the provided key is found. If no value is found
1150 /// or the Json value is not an Object, returns `None`.
1151 pub fn search(&self, key: &str) -> Option<&Json> {
1153 Json::Object(ref map) => match map.get(key) {
1154 Some(json_value) => Some(json_value),
1156 for v in map.values() {
1157 match v.search(key) {
1158 x if x.is_some() => return x,
1169 /// Returns `true` if the Json value is an `Object`.
1170 pub fn is_object(&self) -> bool {
1171 self.as_object().is_some()
1174 /// If the Json value is an `Object`, returns the associated `BTreeMap`;
1175 /// returns `None` otherwise.
1176 pub fn as_object(&self) -> Option<&Object> {
1178 Json::Object(ref map) => Some(map),
1183 /// Returns `true` if the Json value is an `Array`.
1184 pub fn is_array(&self) -> bool {
1185 self.as_array().is_some()
1188 /// If the Json value is an `Array`, returns the associated vector;
1189 /// returns `None` otherwise.
1190 pub fn as_array(&self) -> Option<&Array> {
1192 Json::Array(ref array) => Some(&*array),
1197 /// Returns `true` if the Json value is a `String`.
1198 pub fn is_string(&self) -> bool {
1199 self.as_string().is_some()
1202 /// If the Json value is a `String`, returns the associated `str`;
1203 /// returns `None` otherwise.
1204 pub fn as_string(&self) -> Option<&str> {
1206 Json::String(ref s) => Some(&s[..]),
1211 /// Returns `true` if the Json value is a `Number`.
1212 pub fn is_number(&self) -> bool {
1213 matches!(*self, Json::I64(_) | Json::U64(_) | Json::F64(_))
1216 /// Returns `true` if the Json value is an `i64`.
1217 pub fn is_i64(&self) -> bool {
1218 matches!(*self, Json::I64(_))
1221 /// Returns `true` if the Json value is a `u64`.
1222 pub fn is_u64(&self) -> bool {
1223 matches!(*self, Json::U64(_))
1226 /// Returns `true` if the Json value is a `f64`.
1227 pub fn is_f64(&self) -> bool {
1228 matches!(*self, Json::F64(_))
1231 /// If the Json value is a number, returns or cast it to an `i64`;
1232 /// returns `None` otherwise.
1233 pub fn as_i64(&self) -> Option<i64> {
1235 Json::I64(n) => Some(n),
1236 Json::U64(n) => Some(n as i64),
1241 /// If the Json value is a number, returns or cast it to a `u64`;
1242 /// returns `None` otherwise.
1243 pub fn as_u64(&self) -> Option<u64> {
1245 Json::I64(n) => Some(n as u64),
1246 Json::U64(n) => Some(n),
1251 /// If the Json value is a number, returns or cast it to a `f64`;
1252 /// returns `None` otherwise.
1253 pub fn as_f64(&self) -> Option<f64> {
1255 Json::I64(n) => Some(n as f64),
1256 Json::U64(n) => Some(n as f64),
1257 Json::F64(n) => Some(n),
1262 /// Returns `true` if the Json value is a `Boolean`.
1263 pub fn is_boolean(&self) -> bool {
1264 self.as_boolean().is_some()
1267 /// If the Json value is a `Boolean`, returns the associated `bool`;
1268 /// returns `None` otherwise.
1269 pub fn as_boolean(&self) -> Option<bool> {
1271 Json::Boolean(b) => Some(b),
1276 /// Returns `true` if the Json value is a `Null`.
1277 pub fn is_null(&self) -> bool {
1278 self.as_null().is_some()
1281 /// If the Json value is a `Null`, returns `()`;
1282 /// returns `None` otherwise.
1283 pub fn as_null(&self) -> Option<()> {
1285 Json::Null => Some(()),
1291 impl<'a> Index<&'a str> for Json {
1294 fn index(&self, idx: &'a str) -> &Json {
1295 self.find(idx).unwrap()
1299 impl Index<usize> for Json {
1302 fn index(&self, idx: usize) -> &Json {
1304 Json::Array(ref v) => &v[idx],
1305 _ => panic!("can only index Json with usize if it is an array"),
1310 /// The output of the streaming parser.
1311 #[derive(PartialEq, Clone, Debug)]
1312 pub enum JsonEvent {
1321 StringValue(string::String),
1326 #[derive(PartialEq, Debug)]
1328 // Parse a value in an array, true means first element.
1330 // Parse ',' or ']' after an element in an array.
1332 // Parse a key:value in an object, true means first element.
1334 // Parse ',' or ']' after an element in an object.
1338 // Expecting the stream to end.
1340 // Parsing can't continue.
1344 /// A Stack represents the current position of the parser in the logical
1345 /// structure of the JSON stream.
1347 /// An example is `foo.bar[3].x`.
1350 stack: Vec<InternalStackElement>,
1351 str_buffer: Vec<u8>,
1354 /// StackElements compose a Stack.
1356 /// As an example, `StackElement::Key("foo")`, `StackElement::Key("bar")`,
1357 /// `StackElement::Index(3)`, and `StackElement::Key("x")` are the
1358 /// StackElements composing the stack that represents `foo.bar[3].x`.
1359 #[derive(PartialEq, Clone, Debug)]
1360 pub enum StackElement<'l> {
1365 // Internally, Key elements are stored as indices in a buffer to avoid
1366 // allocating a string for every member of an object.
1367 #[derive(PartialEq, Clone, Debug)]
1368 enum InternalStackElement {
1370 InternalKey(u16, u16), // start, size
1374 pub fn new() -> Stack {
1378 /// Returns The number of elements in the Stack.
1379 pub fn len(&self) -> usize {
1383 /// Returns `true` if the stack is empty.
1384 pub fn is_empty(&self) -> bool {
1385 self.stack.is_empty()
1388 /// Provides access to the StackElement at a given index.
1389 /// lower indices are at the bottom of the stack while higher indices are
1391 pub fn get(&self, idx: usize) -> StackElement<'_> {
1392 match self.stack[idx] {
1393 InternalIndex(i) => StackElement::Index(i),
1394 InternalKey(start, size) => StackElement::Key(
1395 str::from_utf8(&self.str_buffer[start as usize..start as usize + size as usize])
1401 /// Compares this stack with an array of StackElement<'_>s.
1402 pub fn is_equal_to(&self, rhs: &[StackElement<'_>]) -> bool {
1403 if self.stack.len() != rhs.len() {
1406 for (i, r) in rhs.iter().enumerate() {
1407 if self.get(i) != *r {
1414 /// Returns `true` if the bottom-most elements of this stack are the same as
1415 /// the ones passed as parameter.
1416 pub fn starts_with(&self, rhs: &[StackElement<'_>]) -> bool {
1417 if self.stack.len() < rhs.len() {
1420 for (i, r) in rhs.iter().enumerate() {
1421 if self.get(i) != *r {
1428 /// Returns `true` if the top-most elements of this stack are the same as
1429 /// the ones passed as parameter.
1430 pub fn ends_with(&self, rhs: &[StackElement<'_>]) -> bool {
1431 if self.stack.len() < rhs.len() {
1434 let offset = self.stack.len() - rhs.len();
1435 for (i, r) in rhs.iter().enumerate() {
1436 if self.get(i + offset) != *r {
1443 /// Returns the top-most element (if any).
1444 pub fn top(&self) -> Option<StackElement<'_>> {
1445 match self.stack.last() {
1447 Some(&InternalIndex(i)) => Some(StackElement::Index(i)),
1448 Some(&InternalKey(start, size)) => Some(StackElement::Key(
1449 str::from_utf8(&self.str_buffer[start as usize..(start + size) as usize]).unwrap(),
1454 // Used by Parser to insert StackElement::Key elements at the top of the stack.
1455 fn push_key(&mut self, key: string::String) {
1456 self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
1457 self.str_buffer.extend(key.as_bytes());
1460 // Used by Parser to insert StackElement::Index elements at the top of the stack.
1461 fn push_index(&mut self, index: u32) {
1462 self.stack.push(InternalIndex(index));
1465 // Used by Parser to remove the top-most element of the stack.
1467 assert!(!self.is_empty());
1468 match *self.stack.last().unwrap() {
1469 InternalKey(_, sz) => {
1470 let new_size = self.str_buffer.len() - sz as usize;
1471 self.str_buffer.truncate(new_size);
1473 InternalIndex(_) => {}
1478 // Used by Parser to test whether the top-most element is an index.
1479 fn last_is_index(&self) -> bool {
1480 matches!(self.stack.last(), Some(InternalIndex(_)))
1483 // Used by Parser to increment the index of the top-most element.
1484 fn bump_index(&mut self) {
1485 let len = self.stack.len();
1486 let idx = match *self.stack.last().unwrap() {
1487 InternalIndex(i) => i + 1,
1492 self.stack[len - 1] = InternalIndex(idx);
1496 /// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
1497 /// an iterator of char.
1498 pub struct Parser<T> {
1503 // We maintain a stack representing where we are in the logical structure
1504 // of the JSON stream.
1506 // A state machine is kept to make it possible to interrupt and resume parsing.
1510 impl<T: Iterator<Item = char>> Iterator for Parser<T> {
1511 type Item = JsonEvent;
1513 fn next(&mut self) -> Option<JsonEvent> {
1514 if self.state == ParseFinished {
1518 if self.state == ParseBeforeFinish {
1519 self.parse_whitespace();
1520 // Make sure there is no trailing characters.
1522 self.state = ParseFinished;
1525 return Some(self.error_event(TrailingCharacters));
1533 impl<T: Iterator<Item = char>> Parser<T> {
1534 /// Creates the JSON parser.
1535 pub fn new(rdr: T) -> Parser<T> {
1536 let mut p = Parser {
1541 stack: Stack::new(),
1548 /// Provides access to the current position in the logical structure of the
1550 pub fn stack(&self) -> &Stack {
1554 fn eof(&self) -> bool {
1557 fn ch_or_null(&self) -> char {
1558 self.ch.unwrap_or('\x00')
1560 fn bump(&mut self) {
1561 self.ch = self.rdr.next();
1563 if self.ch_is('\n') {
1571 fn next_char(&mut self) -> Option<char> {
1575 fn ch_is(&self, c: char) -> bool {
1579 fn error<U>(&self, reason: ErrorCode) -> Result<U, ParserError> {
1580 Err(SyntaxError(reason, self.line, self.col))
1583 fn parse_whitespace(&mut self) {
1584 while self.ch_is(' ') || self.ch_is('\n') || self.ch_is('\t') || self.ch_is('\r') {
1589 fn parse_number(&mut self) -> JsonEvent {
1590 let neg = if self.ch_is('-') {
1597 let res = match self.parse_u64() {
1604 if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
1605 let mut res = res as f64;
1607 if self.ch_is('.') {
1608 res = match self.parse_decimal(res) {
1616 if self.ch_is('e') || self.ch_is('E') {
1617 res = match self.parse_exponent(res) {
1631 let res = (res as i64).wrapping_neg();
1633 // Make sure we didn't underflow.
1635 Error(SyntaxError(InvalidNumber, self.line, self.col))
1644 fn parse_u64(&mut self) -> Result<u64, ParserError> {
1645 let mut accum = 0u64;
1646 let last_accum = 0; // necessary to detect overflow.
1648 match self.ch_or_null() {
1652 // A leading '0' must be the only digit before the decimal point.
1653 if let '0'..='9' = self.ch_or_null() {
1654 return self.error(InvalidNumber);
1659 match self.ch_or_null() {
1661 accum = accum.wrapping_mul(10);
1662 accum = accum.wrapping_add((c as u64) - ('0' as u64));
1664 // Detect overflow by comparing to the last value.
1665 if accum <= last_accum {
1666 return self.error(InvalidNumber);
1675 _ => return self.error(InvalidNumber),
1681 fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
1684 // Make sure a digit follows the decimal place.
1685 match self.ch_or_null() {
1687 _ => return self.error(InvalidNumber),
1692 match self.ch_or_null() {
1695 res += (((c as isize) - ('0' as isize)) as f64) * dec;
1705 fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
1709 let mut neg_exp = false;
1711 if self.ch_is('+') {
1713 } else if self.ch_is('-') {
1718 // Make sure a digit follows the exponent place.
1719 match self.ch_or_null() {
1721 _ => return self.error(InvalidNumber),
1724 match self.ch_or_null() {
1727 exp += (c as usize) - ('0' as usize);
1735 let exp = 10_f64.powi(exp as i32);
1745 fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
1748 while i < 4 && !self.eof() {
1750 n = match self.ch_or_null() {
1751 c @ '0'..='9' => n * 16 + ((c as u16) - ('0' as u16)),
1752 'a' | 'A' => n * 16 + 10,
1753 'b' | 'B' => n * 16 + 11,
1754 'c' | 'C' => n * 16 + 12,
1755 'd' | 'D' => n * 16 + 13,
1756 'e' | 'E' => n * 16 + 14,
1757 'f' | 'F' => n * 16 + 15,
1758 _ => return self.error(InvalidEscape),
1764 // Error out if we didn't parse 4 digits.
1766 return self.error(InvalidEscape);
1772 fn parse_str(&mut self) -> Result<string::String, ParserError> {
1773 let mut escape = false;
1774 let mut res = string::String::new();
1779 return self.error(EOFWhileParsingString);
1783 match self.ch_or_null() {
1784 '"' => res.push('"'),
1785 '\\' => res.push('\\'),
1786 '/' => res.push('/'),
1787 'b' => res.push('\x08'),
1788 'f' => res.push('\x0c'),
1789 'n' => res.push('\n'),
1790 'r' => res.push('\r'),
1791 't' => res.push('\t'),
1792 'u' => match self.decode_hex_escape()? {
1793 0xDC00..=0xDFFF => return self.error(LoneLeadingSurrogateInHexEscape),
1795 // Non-BMP characters are encoded as a sequence of
1796 // two hex escapes, representing UTF-16 surrogates.
1797 n1 @ 0xD800..=0xDBFF => {
1798 match (self.next_char(), self.next_char()) {
1799 (Some('\\'), Some('u')) => (),
1800 _ => return self.error(UnexpectedEndOfHexEscape),
1803 let n2 = self.decode_hex_escape()?;
1804 if !(0xDC00..=0xDFFF).contains(&n2) {
1805 return self.error(LoneLeadingSurrogateInHexEscape);
1808 (u32::from(n1 - 0xD800) << 10 | u32::from(n2 - 0xDC00)) + 0x1_0000;
1809 res.push(char::from_u32(c).unwrap());
1812 n => match char::from_u32(u32::from(n)) {
1813 Some(c) => res.push(c),
1814 None => return self.error(InvalidUnicodeCodePoint),
1817 _ => return self.error(InvalidEscape),
1820 } else if self.ch_is('\\') {
1828 Some(c) => res.push(c),
1829 None => unreachable!(),
1835 // Invoked at each iteration, consumes the stream until it has enough
1836 // information to return a JsonEvent.
1837 // Manages an internal state so that parsing can be interrupted and resumed.
1838 // Also keeps track of the position in the logical structure of the json
1839 // stream isize the form of a stack that can be queried by the user using the
1841 fn parse(&mut self) -> JsonEvent {
1843 // The only paths where the loop can spin a new iteration
1844 // are in the cases ParseArrayComma and ParseObjectComma if ','
1845 // is parsed. In these cases the state is set to (respectively)
1846 // ParseArray(false) and ParseObject(false), which always return,
1847 // so there is no risk of getting stuck in an infinite loop.
1848 // All other paths return before the end of the loop's iteration.
1849 self.parse_whitespace();
1853 return self.parse_start();
1855 ParseArray(first) => {
1856 return self.parse_array(first);
1858 ParseArrayComma => {
1859 if let Some(evt) = self.parse_array_comma_or_end() {
1863 ParseObject(first) => {
1864 return self.parse_object(first);
1866 ParseObjectComma => {
1868 if self.ch_is(',') {
1869 self.state = ParseObject(false);
1872 return self.parse_object_end();
1876 return self.error_event(InvalidSyntax);
1882 fn parse_start(&mut self) -> JsonEvent {
1883 let val = self.parse_value();
1884 self.state = match val {
1885 Error(_) => ParseFinished,
1886 ArrayStart => ParseArray(true),
1887 ObjectStart => ParseObject(true),
1888 _ => ParseBeforeFinish,
1893 fn parse_array(&mut self, first: bool) -> JsonEvent {
1894 if self.ch_is(']') {
1896 self.error_event(InvalidSyntax)
1898 self.state = if self.stack.is_empty() {
1900 } else if self.stack.last_is_index() {
1910 self.stack.push_index(0);
1912 let val = self.parse_value();
1913 self.state = match val {
1914 Error(_) => ParseFinished,
1915 ArrayStart => ParseArray(true),
1916 ObjectStart => ParseObject(true),
1917 _ => ParseArrayComma,
1923 fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
1924 if self.ch_is(',') {
1925 self.stack.bump_index();
1926 self.state = ParseArray(false);
1929 } else if self.ch_is(']') {
1931 self.state = if self.stack.is_empty() {
1933 } else if self.stack.last_is_index() {
1940 } else if self.eof() {
1941 Some(self.error_event(EOFWhileParsingArray))
1943 Some(self.error_event(InvalidSyntax))
1947 fn parse_object(&mut self, first: bool) -> JsonEvent {
1948 if self.ch_is('}') {
1950 if self.stack.is_empty() {
1951 return self.error_event(TrailingComma);
1956 self.state = if self.stack.is_empty() {
1958 } else if self.stack.last_is_index() {
1967 return self.error_event(EOFWhileParsingObject);
1969 if !self.ch_is('"') {
1970 return self.error_event(KeyMustBeAString);
1972 let s = match self.parse_str() {
1975 self.state = ParseFinished;
1979 self.parse_whitespace();
1981 return self.error_event(EOFWhileParsingObject);
1982 } else if self.ch_or_null() != ':' {
1983 return self.error_event(ExpectedColon);
1985 self.stack.push_key(s);
1987 self.parse_whitespace();
1989 let val = self.parse_value();
1991 self.state = match val {
1992 Error(_) => ParseFinished,
1993 ArrayStart => ParseArray(true),
1994 ObjectStart => ParseObject(true),
1995 _ => ParseObjectComma,
2000 fn parse_object_end(&mut self) -> JsonEvent {
2001 if self.ch_is('}') {
2002 self.state = if self.stack.is_empty() {
2004 } else if self.stack.last_is_index() {
2011 } else if self.eof() {
2012 self.error_event(EOFWhileParsingObject)
2014 self.error_event(InvalidSyntax)
2018 fn parse_value(&mut self) -> JsonEvent {
2020 return self.error_event(EOFWhileParsingValue);
2022 match self.ch_or_null() {
2023 'n' => self.parse_ident("ull", NullValue),
2024 't' => self.parse_ident("rue", BooleanValue(true)),
2025 'f' => self.parse_ident("alse", BooleanValue(false)),
2026 '0'..='9' | '-' => self.parse_number(),
2027 '"' => match self.parse_str() {
2028 Ok(s) => StringValue(s),
2039 _ => self.error_event(InvalidSyntax),
2043 fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
2044 if ident.chars().all(|c| Some(c) == self.next_char()) {
2048 Error(SyntaxError(InvalidSyntax, self.line, self.col))
2052 fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
2053 self.state = ParseFinished;
2054 Error(SyntaxError(reason, self.line, self.col))
2058 /// A Builder consumes a json::Parser to create a generic Json structure.
2059 pub struct Builder<T> {
2061 token: Option<JsonEvent>,
2064 impl<T: Iterator<Item = char>> Builder<T> {
2065 /// Creates a JSON Builder.
2066 pub fn new(src: T) -> Builder<T> {
2067 Builder { parser: Parser::new(src), token: None }
2070 // Decode a Json value from a Parser.
2071 pub fn build(&mut self) -> Result<Json, BuilderError> {
2073 let result = self.build_value();
2077 Some(Error(ref e)) => {
2078 return Err(e.clone());
2081 panic!("unexpected token {:?}", tok.clone());
2087 fn bump(&mut self) {
2088 self.token = self.parser.next();
2091 fn build_value(&mut self) -> Result<Json, BuilderError> {
2093 Some(NullValue) => Ok(Json::Null),
2094 Some(I64Value(n)) => Ok(Json::I64(n)),
2095 Some(U64Value(n)) => Ok(Json::U64(n)),
2096 Some(F64Value(n)) => Ok(Json::F64(n)),
2097 Some(BooleanValue(b)) => Ok(Json::Boolean(b)),
2098 Some(StringValue(ref mut s)) => {
2099 let mut temp = string::String::new();
2101 Ok(Json::String(temp))
2103 Some(Error(ref e)) => Err(e.clone()),
2104 Some(ArrayStart) => self.build_array(),
2105 Some(ObjectStart) => self.build_object(),
2106 Some(ObjectEnd) => self.parser.error(InvalidSyntax),
2107 Some(ArrayEnd) => self.parser.error(InvalidSyntax),
2108 None => self.parser.error(EOFWhileParsingValue),
2112 fn build_array(&mut self) -> Result<Json, BuilderError> {
2114 let mut values = Vec::new();
2117 if self.token == Some(ArrayEnd) {
2118 return Ok(Json::Array(values.into_iter().collect()));
2120 match self.build_value() {
2121 Ok(v) => values.push(v),
2122 Err(e) => return Err(e),
2128 fn build_object(&mut self) -> Result<Json, BuilderError> {
2131 let mut values = BTreeMap::new();
2135 Some(ObjectEnd) => {
2136 return Ok(Json::Object(values));
2138 Some(Error(ref e)) => {
2139 return Err(e.clone());
2146 let key = match self.parser.stack().top() {
2147 Some(StackElement::Key(k)) => k.to_owned(),
2149 panic!("invalid state");
2152 match self.build_value() {
2154 values.insert(key, value);
2162 self.parser.error(EOFWhileParsingObject)
2166 /// Decodes a json value from an `&mut io::Read`
2167 pub fn from_reader(rdr: &mut dyn Read) -> Result<Json, BuilderError> {
2168 let mut contents = Vec::new();
2169 match rdr.read_to_end(&mut contents) {
2171 Err(e) => return Err(io_error_to_error(e)),
2173 let s = match str::from_utf8(&contents).ok() {
2175 _ => return Err(SyntaxError(NotUtf8, 0, 0)),
2177 let mut builder = Builder::new(s.chars());
2181 /// Decodes a json value from a string
2182 pub fn from_str(s: &str) -> Result<Json, BuilderError> {
2183 let mut builder = Builder::new(s.chars());
2187 /// A structure to decode JSON to values in rust.
2188 pub struct Decoder {
2193 /// Creates a new decoder instance for decoding the specified JSON value.
2194 pub fn new(json: Json) -> Decoder {
2195 Decoder { stack: vec![json] }
2198 fn pop(&mut self) -> Json {
2199 self.stack.pop().unwrap()
2203 macro_rules! expect {
2204 ($e:expr, Null) => {{
2207 other => bad!(ExpectedError("Null".to_owned(), other.to_string())),
2210 ($e:expr, $t:ident) => {{
2213 other => bad!(ExpectedError(stringify!($t).to_owned(), other.to_string())),
2218 macro_rules! read_primitive {
2219 ($name:ident, $ty:ty) => {
2220 fn $name(&mut self) -> $ty {
2222 Json::I64(f) => f as $ty,
2223 Json::U64(f) => f as $ty,
2224 Json::F64(f) => bad!(ExpectedError("Integer".to_owned(), f.to_string())),
2225 // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
2226 // is going to have a string here, as per JSON spec.
2227 Json::String(s) => match s.parse().ok() {
2229 None => bad!(ExpectedError("Number".to_owned(), s)),
2231 value => bad!(ExpectedError("Number".to_owned(), value.to_string())),
2237 impl crate::Decoder for Decoder {
2238 fn read_unit(&mut self) -> () {
2239 expect!(self.pop(), Null)
2242 read_primitive! { read_usize, usize }
2243 read_primitive! { read_u8, u8 }
2244 read_primitive! { read_u16, u16 }
2245 read_primitive! { read_u32, u32 }
2246 read_primitive! { read_u64, u64 }
2247 read_primitive! { read_u128, u128 }
2248 read_primitive! { read_isize, isize }
2249 read_primitive! { read_i8, i8 }
2250 read_primitive! { read_i16, i16 }
2251 read_primitive! { read_i32, i32 }
2252 read_primitive! { read_i64, i64 }
2253 read_primitive! { read_i128, i128 }
2255 fn read_f32(&mut self) -> f32 {
2256 self.read_f64() as f32
2259 fn read_f64(&mut self) -> f64 {
2261 Json::I64(f) => f as f64,
2262 Json::U64(f) => f as f64,
2264 Json::String(s) => {
2265 // re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
2266 // is going to have a string here, as per JSON spec.
2267 match s.parse().ok() {
2269 None => bad!(ExpectedError("Number".to_owned(), s)),
2272 Json::Null => f64::NAN,
2273 value => bad!(ExpectedError("Number".to_owned(), value.to_string())),
2277 fn read_bool(&mut self) -> bool {
2278 expect!(self.pop(), Boolean)
2281 fn read_char(&mut self) -> char {
2282 let s = self.read_str();
2283 let mut it = s.chars();
2284 if let (Some(c), None) = (it.next(), it.next()) {
2285 // exactly one character
2288 bad!(ExpectedError("single character string".to_owned(), s.to_string()));
2291 fn read_str(&mut self) -> Cow<'_, str> {
2292 Cow::Owned(expect!(self.pop(), String))
2295 fn read_raw_bytes_into(&mut self, s: &mut [u8]) {
2296 for c in s.iter_mut() {
2297 *c = self.read_u8();
2301 fn read_enum<T, F>(&mut self, f: F) -> T
2303 F: FnOnce(&mut Decoder) -> T,
2308 fn read_enum_variant<T, F>(&mut self, names: &[&str], mut f: F) -> T
2310 F: FnMut(&mut Decoder, usize) -> T,
2312 let name = match self.pop() {
2313 Json::String(s) => s,
2314 Json::Object(mut o) => {
2315 let n = match o.remove("variant") {
2316 Some(Json::String(s)) => s,
2317 Some(val) => bad!(ExpectedError("String".to_owned(), val.to_string())),
2318 None => bad!(MissingFieldError("variant".to_owned())),
2320 match o.remove("fields") {
2321 Some(Json::Array(l)) => {
2322 self.stack.extend(l.into_iter().rev());
2324 Some(val) => bad!(ExpectedError("Array".to_owned(), val.to_string())),
2325 None => bad!(MissingFieldError("fields".to_owned())),
2329 json => bad!(ExpectedError("String or Object".to_owned(), json.to_string())),
2331 let idx = match names.iter().position(|n| *n == &name[..]) {
2333 None => bad!(UnknownVariantError(name)),
2338 fn read_enum_variant_arg<T, F>(&mut self, f: F) -> T
2340 F: FnOnce(&mut Decoder) -> T,
2345 fn read_struct<T, F>(&mut self, f: F) -> T
2347 F: FnOnce(&mut Decoder) -> T,
2349 let value = f(self);
2354 fn read_struct_field<T, F>(&mut self, name: &str, f: F) -> T
2356 F: FnOnce(&mut Decoder) -> T,
2358 let mut obj = expect!(self.pop(), Object);
2360 let value = match obj.remove(name) {
2362 // Add a Null and try to parse it as an Option<_>
2363 // to get None as a default value.
2364 self.stack.push(Json::Null);
2368 self.stack.push(json);
2372 self.stack.push(Json::Object(obj));
2376 fn read_tuple<T, F>(&mut self, tuple_len: usize, f: F) -> T
2378 F: FnOnce(&mut Decoder) -> T,
2380 self.read_seq(move |d, len| {
2381 if len == tuple_len {
2384 bad!(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)));
2389 fn read_tuple_arg<T, F>(&mut self, f: F) -> T
2391 F: FnOnce(&mut Decoder) -> T,
2393 self.read_seq_elt(f)
2396 fn read_option<T, F>(&mut self, mut f: F) -> T
2398 F: FnMut(&mut Decoder, bool) -> T,
2401 Json::Null => f(self, false),
2403 self.stack.push(value);
2409 fn read_seq<T, F>(&mut self, f: F) -> T
2411 F: FnOnce(&mut Decoder, usize) -> T,
2413 let array = expect!(self.pop(), Array);
2414 let len = array.len();
2415 self.stack.extend(array.into_iter().rev());
2419 fn read_seq_elt<T, F>(&mut self, f: F) -> T
2421 F: FnOnce(&mut Decoder) -> T,
2426 fn read_map<T, F>(&mut self, f: F) -> T
2428 F: FnOnce(&mut Decoder, usize) -> T,
2430 let obj = expect!(self.pop(), Object);
2431 let len = obj.len();
2432 for (key, value) in obj {
2433 self.stack.push(value);
2434 self.stack.push(Json::String(key));
2439 fn read_map_elt_key<T, F>(&mut self, f: F) -> T
2441 F: FnOnce(&mut Decoder) -> T,
2446 fn read_map_elt_val<T, F>(&mut self, f: F) -> T
2448 F: FnOnce(&mut Decoder) -> T,
2454 /// A trait for converting values to JSON
2456 /// Converts the value of `self` to an instance of JSON
2457 fn to_json(&self) -> Json;
2460 macro_rules! to_json_impl_i64 {
2462 $(impl ToJson for $t {
2463 fn to_json(&self) -> Json {
2464 Json::I64(*self as i64)
2470 to_json_impl_i64! { isize, i8, i16, i32, i64 }
2472 macro_rules! to_json_impl_u64 {
2474 $(impl ToJson for $t {
2475 fn to_json(&self) -> Json {
2476 Json::U64(*self as u64)
2482 to_json_impl_u64! { usize, u8, u16, u32, u64 }
2484 impl ToJson for Json {
2485 fn to_json(&self) -> Json {
2490 impl ToJson for f32 {
2491 fn to_json(&self) -> Json {
2492 f64::from(*self).to_json()
2496 impl ToJson for f64 {
2497 fn to_json(&self) -> Json {
2498 match self.classify() {
2499 Fp::Nan | Fp::Infinite => Json::Null,
2500 _ => Json::F64(*self),
2505 impl ToJson for () {
2506 fn to_json(&self) -> Json {
2511 impl ToJson for bool {
2512 fn to_json(&self) -> Json {
2513 Json::Boolean(*self)
2517 impl ToJson for str {
2518 fn to_json(&self) -> Json {
2519 Json::String(self.to_string())
2523 impl ToJson for string::String {
2524 fn to_json(&self) -> Json {
2525 Json::String((*self).clone())
2529 macro_rules! tuple_impl {
2530 // use variables to indicate the arity of the tuple
2531 ($($tyvar:ident),* ) => {
2532 // the trailing commas are for the 1 tuple
2534 $( $tyvar : ToJson ),*
2535 > ToJson for ( $( $tyvar ),* , ) {
2538 #[allow(non_snake_case)]
2539 fn to_json(&self) -> Json {
2541 ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
2550 tuple_impl! {A, B, C}
2551 tuple_impl! {A, B, C, D}
2552 tuple_impl! {A, B, C, D, E}
2553 tuple_impl! {A, B, C, D, E, F}
2554 tuple_impl! {A, B, C, D, E, F, G}
2555 tuple_impl! {A, B, C, D, E, F, G, H}
2556 tuple_impl! {A, B, C, D, E, F, G, H, I}
2557 tuple_impl! {A, B, C, D, E, F, G, H, I, J}
2558 tuple_impl! {A, B, C, D, E, F, G, H, I, J, K}
2559 tuple_impl! {A, B, C, D, E, F, G, H, I, J, K, L}
2561 impl<A: ToJson> ToJson for [A] {
2562 fn to_json(&self) -> Json {
2563 Json::Array(self.iter().map(|elt| elt.to_json()).collect())
2567 impl<A: ToJson> ToJson for Vec<A> {
2568 fn to_json(&self) -> Json {
2569 Json::Array(self.iter().map(|elt| elt.to_json()).collect())
2573 impl<T: ToString, A: ToJson> ToJson for BTreeMap<T, A> {
2574 fn to_json(&self) -> Json {
2575 let mut d = BTreeMap::new();
2576 for (key, value) in self {
2577 d.insert(key.to_string(), value.to_json());
2583 impl<A: ToJson> ToJson for HashMap<string::String, A> {
2584 fn to_json(&self) -> Json {
2585 let mut d = BTreeMap::new();
2586 for (key, value) in self {
2587 d.insert((*key).clone(), value.to_json());
2593 impl<A: ToJson> ToJson for Option<A> {
2594 fn to_json(&self) -> Json {
2597 Some(ref value) => value.to_json(),
2602 struct FormatShim<'a, 'b> {
2603 inner: &'a mut fmt::Formatter<'b>,
2606 impl<'a, 'b> fmt::Write for FormatShim<'a, 'b> {
2607 fn write_str(&mut self, s: &str) -> fmt::Result {
2608 match self.inner.write_str(s) {
2610 Err(_) => Err(fmt::Error),
2615 impl fmt::Display for Json {
2616 /// Encodes a json value into a string
2617 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2618 let mut shim = FormatShim { inner: f };
2619 let mut encoder = Encoder::new(&mut shim);
2620 match self.encode(&mut encoder) {
2622 Err(_) => Err(fmt::Error),
2627 impl<'a> fmt::Display for PrettyJson<'a> {
2628 /// Encodes a json value into a string
2629 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2630 let mut shim = FormatShim { inner: f };
2631 let mut encoder = PrettyEncoder::new(&mut shim);
2632 match self.inner.encode(&mut encoder) {
2634 Err(_) => Err(fmt::Error),
2639 impl<'a, T: for<'r> Encodable<Encoder<'r>>> fmt::Display for AsJson<'a, T> {
2640 /// Encodes a json value into a string
2641 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2642 let mut shim = FormatShim { inner: f };
2643 let mut encoder = Encoder::new(&mut shim);
2644 match self.inner.encode(&mut encoder) {
2646 Err(_) => Err(fmt::Error),
2651 impl<'a, T> AsPrettyJson<'a, T> {
2652 /// Sets the indentation level for the emitted JSON
2653 pub fn indent(mut self, indent: usize) -> AsPrettyJson<'a, T> {
2654 self.indent = Some(indent);
2659 impl<'a, T: for<'x> Encodable<PrettyEncoder<'x>>> fmt::Display for AsPrettyJson<'a, T> {
2660 /// Encodes a json value into a string
2661 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2662 let mut shim = FormatShim { inner: f };
2663 let mut encoder = PrettyEncoder::new(&mut shim);
2664 if let Some(n) = self.indent {
2665 encoder.set_indent(n);
2667 match self.inner.encode(&mut encoder) {
2669 Err(_) => Err(fmt::Error),
2674 impl FromStr for Json {
2675 type Err = BuilderError;
2676 fn from_str(s: &str) -> Result<Json, BuilderError> {