tinyjson
tinyjson is a library to parse/generate JSON format document.
Goals:
- Using Stable APIs; using no experimental APIs, no compiler plugin.
- Reasonable simple JSON object interface; not serialize/deserialize JSON format to some specific
struct
. - Dependency free.
- My Rust practice :)
Usage
Parse JSON
String is parsed to JsonValue
struct.
use parse;
let s = r#"
{
"bool": true,
"arr": [1, null, "test"],
"nested": {
"blah": false,
"blahblah": 3.14
},
"unicode": "\u2764"
}
"#;
let parsed = parse;
println!;
tinyjson::parser::parse()
is available for &String
and &'a str
. It parses the target as JSON and creates tinyjson::JsonValue
object. It represents tree structure of parsed JSON. JsonValue
is an enum
struct and allocated on stack. So it doesn't require additional heap allocation.
Access to JSON Value
JsonValue
is an enum
value. So we can access it with match
statement.
let json = Number;
let v = match json ;
But JSON is a tree structure and it's boring to write nested match
statement. So JsonValue
meets std::ops::Index
trait in order to access to its value quickly.
let complicated_json = parse;
let target_value = complicated_json;
println!; // => JsonValue::Number(42.0)
Index access with String
or str
key is available when the value is an object. And Index access with usize
is available when the value is an array. They return the &JsonValue
value if target value was found.
When the value for key or the element of index was not found, it will call panic!
.
Additionally, get()
method is provided to dereference the enum
value (e.g. JsonValue::Number(4.2)
-> 4.2
).
let json = parse;
let ref num: f64 = json.get.expect;
let ref arr: = json.get.expect;
let ref null: = json.get.expect;
print!;
get()
method returns its dereferenced raw value. It returns Option<&T>
(T
is corresponding value that you expected). If None
is returned, it means its type mismatched with your expected one. Which type get()
should dereference is inferred from how the returned value will be handled. So you need not to specify it explicitly.
Equality of JsonValue
JsonValue
drives PartialEq
traits hence it can be checked with ==
operator.
let json = parse;
assert!;
If you want to check its type only, there are is_xxx()
shortcut methods in JsonValue
instead of using match
statement explicitly.
let json = parse;
assert!;
assert!;
assert!;
Generate JSON
to_string()
method can be used to create JSON string from JsonValue
.
use parse;
use to_string;
let s = r#"
{
"bool": true,
"arr": [1, null, "test"],
"nested": {
"blah": false,
"blahblah": 3.14
},
"unicode": "\u2764"
}
"#;
let parsed = parse;
let str = parsed.to_string;
println!;
TODO
- Parser
- Generator
- Read from file descriptor
- Equality of
JsonValue
- Index access to
JsonValue
(array, object) - Tests