Skip to content

reinfer/spanned-json-parser

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

36 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Spanned Json Parser   Build Status Latest Version

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 a 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]

About

🔨 A JSON parser that will return span information

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Rust 100.0%