Crates.io | jsonc-to-json |
lib.rs | jsonc-to-json |
version | 0.1.1 |
source | src |
created_at | 2023-06-23 13:17:56.69576 |
updated_at | 2023-06-23 13:50:09.450209 |
description | Simple library for converting JSONC into JSON |
homepage | |
repository | https://github.com/vallentin/jsonc-to-json |
max_upload_size | |
id | 898257 |
size | 25,623 |
Simple library for converting JSON with Comments into JSON, in short it removes the following:
// Line Comment
/* Block Comment */
[1,2,3,,]
-> [1,2,3]
Note: The implementation does not use a full-blown JSON with Comments parser. Instead it uses a JSON with Comments tokenizer, which makes conversion a lot faster.
Currently #![no_std]
is not supported. It will however be added, when
some upstream changes have been applied.
See jsonc_to_json()
for more information.
use jsonc_to_json::{jsonc_to_json, jsonc_to_json_into};
let jsonc = "{\"arr\": [1, 2,/* Comment */ 3, 4,,]}// Line Comment";
let json = jsonc_to_json(jsonc);
println!("{}", json);
// Alternatively, use `jsonc_to_json_into()` to reuse an
// already allocated `String`
let mut json = String::new();
jsonc_to_json_into(jsonc, &mut json);
println!("{}", json);
Both output the following:
{"arr": [1, 2, 3, 4]}
use jsonc_to_json::{jsonc_to_json, jsonc_to_json_into};
use serde::Deserialize;
#[derive(Deserialize, Debug)]
struct Data {
arr: Vec<i32>,
}
let jsonc = "{\"arr\": [1, 2,/* Comment */ 3, 4,,]}// Line Comment";
let json = jsonc_to_json(jsonc);
let data: Data = serde_json::from_str(&json)?;
println!("{}", json);
println!("{:?}", data);
Which outputs the following:
{"arr": [1, 2, 3, 4]}
Data { arr: [1, 2, 3, 4] }
Non-allocating Iterator
that yields string slices of
valid JSON.
use jsonc_to_json::jsonc_to_json_iter;
let jsonc = r#"{foo}/**/[1,2,3,,]"bar""#;
let mut iter = jsonc_to_json_iter(jsonc);
assert_eq!(iter.next(), Some("{foo}")); // Line comment was removed
assert_eq!(iter.next(), Some("[1,2,3")); // Trailing commas was removed
assert_eq!(iter.next(), Some("]\"bar\""));
assert_eq!(iter.next(), None);