spanned_json_parser

Crates.iospanned_json_parser
lib.rsspanned_json_parser
version0.2.0
sourcesrc
created_at2023-11-06 14:39:31.510926
updated_at2023-11-10 15:21:58.038092
descriptionA Json parser that gives you the line and column number for each value
homepage
repositoryhttps://github.com/JulesGuesnon/spanned-json-parser
max_upload_size
id1026975
size52,158
Jules Guesnon (JulesGuesnon)

documentation

README

Spanned Json Parser

This crate is a json parser that will return span information for values, which mean lines and column number. It is also compatible with serde so you can serialize it to any other struct that implements Deserialize

Why use it ?

One of the main use case is to do validation after parsing. By having the line and col number, you can tell really precisely to user where a value is invalid

How to use it ?

The crate expose a Value that is similar to serde, and wraps everything into this struct:

pub struct Position {
    pub col: usize,
    pub line: usize,
}

pub struct SpannedValue {
    pub value: Value,
    pub start: Position,
    pub end: Position,
}

Parsing

use spanned_json_parse::parse;
use std::fs;

fn main() {
    let json = fs::read_to_string(path).unwrap();

    let parsed = parse(&json);

    println!("Parsed: {:#?}", parsed);
}

Serializing in a struct

use serde::Deserialize;
use spanned_json_parser::parse;

#[derive(Deserialize)]
struct Test {
    pub hello: String,
}

fn main() {
    let json = r#"{"hello": "world"}"#;

    let parsed = parse(json).unwrap();

    let test: Test = serde_json::from_value(serde_json::to_value(parsed).unwrap()).unwrap();

    println!("Test hello: {}", test.hello);
}

Performance

Here are the outputs of the benchmark. Everything was tested on a Macbook Pro M1, so keep in mind that this numbers are here to give you an idea of the performance, but might not be representative of the reality:

Parser ./benches/data/twitter.json
time:   [10.220 ms 10.279 ms 10.334 ms]
thrpt:  [58.280 MiB/s 58.589 MiB/s 58.932 MiB/s]

Parser ./benches/data/citm_catalog.json
time:   [18.204 ms 18.281 ms 18.353 ms]
thrpt:  [89.752 MiB/s 90.102 MiB/s 90.486 MiB/s]

Parser ./benches/data/canada.json
time:   [42.026 ms 42.188 ms 42.341 ms]
thrpt:  [50.702 MiB/s 50.886 MiB/s 51.082 MiB/s]
Commit count: 36

cargo fmt