json_joxit_fork/lib.rs
1//! 
2//!
3//! # json-rust
4//!
5//! Parse and serialize [JSON](http://json.org/) with ease.
6//!
7//! **[Changelog](https://github.com/maciejhirsz/json-rust/releases) -**
8//! **[Complete Documentation](https://docs.rs/json/) -**
9//! **[Cargo](https://crates.io/crates/json) -**
10//! **[Repository](https://github.com/maciejhirsz/json-rust)**
11//!
12//! ## Why?
13//!
14//! JSON is a very loose format where anything goes - arrays can hold mixed
15//! types, object keys can change types between API calls or not include
16//! some keys under some conditions. Mapping that to idiomatic Rust structs
17//! introduces friction.
18//!
19//! This crate intends to avoid that friction.
20//!
21//! ```rust
22//! # #[macro_use] extern crate json;
23//! # fn main() {
24//! let parsed = json::parse(r#"
25//!
26//! {
27//! "code": 200,
28//! "success": true,
29//! "payload": {
30//! "features": [
31//! "awesome",
32//! "easyAPI",
33//! "lowLearningCurve"
34//! ]
35//! }
36//! }
37//!
38//! "#).unwrap();
39//!
40//! let instantiated = object!{
41//! "code" => 200,
42//! "success" => true,
43//! "payload" => object!{
44//! "features" => array![
45//! "awesome",
46//! "easyAPI",
47//! "lowLearningCurve"
48//! ]
49//! }
50//! };
51//!
52//! assert_eq!(parsed, instantiated);
53//! # }
54//! ```
55//!
56//! ## First class citizen
57//!
58//! Using macros and indexing, it's easy to work with the data.
59//!
60//! ```rust
61//! # #[macro_use] extern crate json;
62//! # fn main() {
63//! let mut data = object!{
64//! "foo" => false,
65//! "bar" => json::Null,
66//! "answer" => 42,
67//! "list" => array![json::Null, "world", true]
68//! };
69//!
70//! // Partial equality is implemented for most raw types:
71//! assert!(data["foo"] == false);
72//!
73//! // And it's type aware, `null` and `false` are different values:
74//! assert!(data["bar"] != false);
75//!
76//! // But you can use any Rust number types:
77//! assert!(data["answer"] == 42);
78//! assert!(data["answer"] == 42.0);
79//! assert!(data["answer"] == 42isize);
80//!
81//! // Access nested structures, arrays and objects:
82//! assert!(data["list"][0].is_null());
83//! assert!(data["list"][1] == "world");
84//! assert!(data["list"][2] == true);
85//!
86//! // Error resilient - accessing properties that don't exist yield null:
87//! assert!(data["this"]["does"]["not"]["exist"].is_null());
88//!
89//! // Mutate by assigning:
90//! data["list"][0] = "Hello".into();
91//!
92//! // Use the `dump` method to serialize the data:
93//! assert_eq!(data.dump(), r#"{"foo":false,"bar":null,"answer":42,"list":["Hello","world",true]}"#);
94//!
95//! // Or pretty print it out:
96//! println!("{:#}", data);
97//! # }
98//! ```
99//!
100//! ## Serialize with `json::stringify(value)`
101//!
102//! Primitives:
103//!
104//! ```
105//! // str slices
106//! assert_eq!(json::stringify("foobar"), "\"foobar\"");
107//!
108//! // Owned strings
109//! assert_eq!(json::stringify("foobar".to_string()), "\"foobar\"");
110//!
111//! // Any number types
112//! assert_eq!(json::stringify(42), "42");
113//!
114//! // Booleans
115//! assert_eq!(json::stringify(true), "true");
116//! assert_eq!(json::stringify(false), "false");
117//! ```
118//!
119//! Explicit `null` type `json::Null`:
120//!
121//! ```
122//! assert_eq!(json::stringify(json::Null), "null");
123//! ```
124//!
125//! Optional types:
126//!
127//! ```
128//! let value: Option<String> = Some("foo".to_string());
129//! assert_eq!(json::stringify(value), "\"foo\"");
130//!
131//! let no_value: Option<String> = None;
132//! assert_eq!(json::stringify(no_value), "null");
133//! ```
134//!
135//! Vector:
136//!
137//! ```
138//! let data = vec![1,2,3];
139//! assert_eq!(json::stringify(data), "[1,2,3]");
140//! ```
141//!
142//! Vector with optional values:
143//!
144//! ```
145//! let data = vec![Some(1), None, Some(2), None, Some(3)];
146//! assert_eq!(json::stringify(data), "[1,null,2,null,3]");
147//! ```
148//!
149//! Pushing to arrays:
150//!
151//! ```
152//! let mut data = json::JsonValue::new_array();
153//!
154//! data.push(10);
155//! data.push("foo");
156//! data.push(false);
157//!
158//! assert_eq!(data.dump(), r#"[10,"foo",false]"#);
159//! ```
160//!
161//! Putting fields on objects:
162//!
163//! ```
164//! let mut data = json::JsonValue::new_object();
165//!
166//! data["answer"] = 42.into();
167//! data["foo"] = "bar".into();
168//!
169//! assert_eq!(data.dump(), r#"{"answer":42,"foo":"bar"}"#);
170//! ```
171//!
172//! `array!` macro:
173//!
174//! ```
175//! # #[macro_use] extern crate json;
176//! # fn main() {
177//! let data = array!["foo", "bar", 100, true, json::Null];
178//! assert_eq!(data.dump(), r#"["foo","bar",100,true,null]"#);
179//! # }
180//! ```
181//!
182//! `object!` macro:
183//!
184//! ```
185//! # #[macro_use] extern crate json;
186//! # fn main() {
187//! let data = object!{
188//! "name" => "John Doe",
189//! "age" => 30,
190//! "canJSON" => true
191//! };
192//! assert_eq!(
193//! data.dump(),
194//! r#"{"name":"John Doe","age":30,"canJSON":true}"#
195//! );
196//! # }
197//! ```
198
199use std::result;
200
201pub mod codegen;
202mod parser;
203mod value;
204mod error;
205mod util;
206
207pub mod short;
208pub mod object;
209pub mod number;
210
211pub use error::Error;
212pub use value::JsonValue;
213pub use value::JsonValue::Null;
214
215/// Result type used by this crate.
216///
217///
218/// *Note:* Since 0.9.0 the old `JsonResult` type is deprecated. Always use
219/// `json::Result` instead.
220pub type Result<T> = result::Result<T, Error>;
221
222pub mod iterators {
223 /// Iterator over members of `JsonValue::Array`.
224 pub type Members<'a> = ::std::slice::Iter<'a, super::JsonValue>;
225
226 /// Mutable iterator over members of `JsonValue::Array`.
227 pub type MembersMut<'a> = ::std::slice::IterMut<'a, super::JsonValue>;
228
229 /// Iterator over key value pairs of `JsonValue::Object`.
230 pub type Entries<'a> = super::object::Iter<'a>;
231
232 /// Mutable iterator over key value pairs of `JsonValue::Object`.
233 pub type EntriesMut<'a> = super::object::IterMut<'a>;
234}
235
236#[deprecated(since="0.9.0", note="use `json::Error` instead")]
237pub use Error as JsonError;
238
239#[deprecated(since="0.9.0", note="use `json::Result` instead")]
240pub use crate::Result as JsonResult;
241
242pub use parser::parse;
243
244pub type Array = Vec<JsonValue>;
245
246/// Convenience for `JsonValue::from(value)`
247pub fn from<T>(value: T) -> JsonValue where T: Into<JsonValue> {
248 value.into()
249}
250
251/// Pretty prints out the value as JSON string.
252pub fn stringify<T>(root: T) -> String where T: Into<JsonValue> {
253 let root: JsonValue = root.into();
254 root.dump()
255}
256
257/// Pretty prints out the value as JSON string. Second argument is a
258/// number of spaces to indent new blocks with.
259pub fn stringify_pretty<T>(root: T, spaces: u16) -> String where T: Into<JsonValue> {
260 let root: JsonValue = root.into();
261 root.pretty(spaces)
262}
263
264/// Helper macro for creating instances of `JsonValue::Array`.
265///
266/// ```
267/// # #[macro_use] extern crate json;
268/// # fn main() {
269/// let data = array!["foo", 42, false];
270///
271/// assert_eq!(data[0], "foo");
272/// assert_eq!(data[1], 42);
273/// assert_eq!(data[2], false);
274///
275/// assert_eq!(data.dump(), r#"["foo",42,false]"#);
276/// # }
277/// ```
278#[macro_export]
279macro_rules! array {
280 [] => ($crate::JsonValue::new_array());
281
282 [ $( $item:expr ),* ] => ({
283 let size = 0 $( + {let _ = $item; 1} )*;
284 let mut array = Vec::with_capacity(size);
285
286 $(
287 array.push($item.into());
288 )*
289
290 $crate::JsonValue::Array(array)
291 })
292}
293
294/// Helper macro for creating instances of `JsonValue::Object`.
295///
296/// ```
297/// # #[macro_use] extern crate json;
298/// # fn main() {
299/// let data = object!{
300/// "foo" => 42,
301/// "bar" => false
302/// };
303///
304/// assert_eq!(data["foo"], 42);
305/// assert_eq!(data["bar"], false);
306///
307/// assert_eq!(data.dump(), r#"{"foo":42,"bar":false}"#);
308/// # }
309/// ```
310#[macro_export]
311macro_rules! object {
312 // Empty object.
313 {} => ($crate::JsonValue::new_object());
314
315 // Non-empty object, no trailing comma.
316 //
317 // In this implementation, key/value pairs separated by commas.
318 { $( $key:expr => $value:expr ),* } => {
319 $crate::object!( $(
320 $key => $value,
321 )* )
322 };
323
324 // Non-empty object, trailing comma.
325 //
326 // In this implementation, the comma is part of the value.
327 { $( $key:expr => $value:expr, )* } => ({
328 use $crate::object::Object;
329
330 let size = 0 $( + {let _ = $key; 1} )*;
331 let mut object = Object::with_capacity(size);
332
333 $(
334 object.insert($key, $value.into());
335 )*
336
337 $crate::JsonValue::Object(object)
338 })
339}
340