json-node

Crates.iojson-node
lib.rsjson-node
version0.2.1
sourcesrc
created_at2023-08-08 14:15:16.502478
updated_at2023-09-04 21:12:38.283199
descriptionA way to work with JSON as a node tree.
homepage
repositoryhttps://github.com/Skyppex/json-node
max_upload_size
id939200
size65,131
Brage Ingebrigtsen (Skyppex)

documentation

README

Json Node

A way to work with JSON as a node tree.

Installation

Navigate to your project folder and run:

cargo add json-node

Now you're set

Usage

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 Values. 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.

Develop

If you want to help develop this crate, clone the repo:

git clone https://github.com/Skyppex/json-node.git

Pull Requests

PRs are welcome :D

Commit count: 20

cargo fmt