[−][src]Crate json
json-rust
Parse and serialize JSON with ease.
Changelog - Complete Documentation - Cargo - Repository
Why?
JSON is a very loose format where anything goes - arrays can hold mixed types, object keys can change types between API calls or not include some keys under some conditions. Mapping that to idiomatic Rust structs introduces friction.
This crate intends to avoid that friction.
let parsed = json::parse(r#" { "code": 200, "success": true, "payload": { "features": [ "awesome", "easyAPI", "lowLearningCurve" ] } } "#).unwrap(); let instantiated = object!{ "code" => 200, "success" => true, "payload" => object!{ "features" => array![ "awesome", "easyAPI", "lowLearningCurve" ] } }; assert_eq!(parsed, instantiated);
First class citizen
Using macros and indexing, it's easy to work with the data.
let mut data = object!{ "foo" => false, "bar" => json::Null, "answer" => 42, "list" => array![json::Null, "world", true] }; // Partial equality is implemented for most raw types: assert!(data["foo"] == false); // And it's type aware, `null` and `false` are different values: assert!(data["bar"] != false); // But you can use any Rust number types: assert!(data["answer"] == 42); assert!(data["answer"] == 42.0); assert!(data["answer"] == 42isize); // Access nested structures, arrays and objects: assert!(data["list"][0].is_null()); assert!(data["list"][1] == "world"); assert!(data["list"][2] == true); // Error resilient - accessing properties that don't exist yield null: assert!(data["this"]["does"]["not"]["exist"].is_null()); // Mutate by assigning: data["list"][0] = "Hello".into(); // Use the `dump` method to serialize the data: assert_eq!(data.dump(), r#"{"foo":false,"bar":null,"answer":42,"list":["Hello","world",true]}"#); // Or pretty print it out: println!("{:#}", data);
Serialize with json::stringify(value)
Primitives:
// str slices assert_eq!(json::stringify("foobar"), "\"foobar\""); // Owned strings assert_eq!(json::stringify("foobar".to_string()), "\"foobar\""); // Any number types assert_eq!(json::stringify(42), "42"); // Booleans assert_eq!(json::stringify(true), "true"); assert_eq!(json::stringify(false), "false");
Explicit null
type json::Null
:
assert_eq!(json::stringify(json::Null), "null");
Optional types:
let value: Option<String> = Some("foo".to_string()); assert_eq!(json::stringify(value), "\"foo\""); let no_value: Option<String> = None; assert_eq!(json::stringify(no_value), "null");
Vector:
let data = vec![1,2,3]; assert_eq!(json::stringify(data), "[1,2,3]");
Vector with optional values:
let data = vec![Some(1), None, Some(2), None, Some(3)]; assert_eq!(json::stringify(data), "[1,null,2,null,3]");
Pushing to arrays:
let mut data = json::JsonValue::new_array(); data.push(10); data.push("foo"); data.push(false); assert_eq!(data.dump(), r#"[10,"foo",false]"#);
Putting fields on objects:
let mut data = json::JsonValue::new_object(); data["answer"] = 42.into(); data["foo"] = "bar".into(); assert_eq!(data.dump(), r#"{"answer":42,"foo":"bar"}"#);
array!
macro:
let data = array!["foo", "bar", 100, true, json::Null]; assert_eq!(data.dump(), r#"["foo","bar",100,true,null]"#);
object!
macro:
let data = object!{ "name" => "John Doe", "age" => 30, "canJSON" => true }; assert_eq!( data.dump(), r#"{"name":"John Doe","age":30,"canJSON":true}"# );
Re-exports
pub use value::JsonValue::Null; |
pub use Result as JsonResult; |
Modules
iterators | |
number | |
object | |
short |
Macros
array | Helper macro for creating instances of |
object | Helper macro for creating instances of |
Enums
Error | Error type of this crate. |
JsonError | Error type of this crate. |
JsonValue |
Functions
from | Convenience for |
parse | |
stringify | Pretty prints out the value as JSON string. |
stringify_pretty | Pretty prints out the value as JSON string. Second argument is a number of spaces to indent new blocks with. |
Type Definitions
Array | |
Result | Result type used by this crate. |