Crates.io | json-node |
lib.rs | json-node |
version | 0.2.1 |
source | src |
created_at | 2023-08-08 14:15:16.502478 |
updated_at | 2023-09-04 21:12:38.283199 |
description | A way to work with JSON as a node tree. |
homepage | |
repository | https://github.com/Skyppex/json-node |
max_upload_size | |
id | 939200 |
size | 65,131 |
A way to work with JSON as a node tree.
Navigate to your project folder and run:
cargo add json-node
Now you're set
Use the JsonNode
type to parse your JSON into nodes. There are three types of nodes: Object
, Array
and JsonValue
. A Value
can have several different types of values: String
, Integer
, Float
, Boolean
, Null
. These are all modeled with enums to ensure type safety, even when a Array
contains different types of Value
s.
After parsing you can dig for what you need manually using the match
statement or if let
as you would with enums normally. Or you can iterate through every value under a node by calling into_iter()
.
use json_node::{JsonNode, JsonValueType};
let json = "[1, 2, 3, 4, 5]";
let tree = JsonNode::parse(json).unwrap();
match tree {
JsonNode::Array(arr) => {
for element in arr.iter() {
println!("{:?}", element);
}
}
_ => println!("Expected node to be an Array.")
}
OR
use json_node::{JsonNode, JsonValueType};
let json = "[1, 2, 3, 4, 5]";
let tree = JsonNode::parse(json).unwrap();
for value in tree.into_iter() {
match value {
JsonNode::Value(value) => {
match value {
JsonValueType::Integer(num) => println!("{num}");
_ => println!("Expected integer value.")
}
}
_ => println!("Expected value.")
}
}
They both output:
1
2
3
4
5
You can also use this API to build a JSON string from nodes if needed. Although it won't be nicely formatted.
If you want to help develop this crate, clone the repo:
git clone https://github.com/Skyppex/json-node.git
PRs are welcome :D