| 1 | # json-comments-rs |
| 2 | |
| 3 | [](https://github.com/tmccombs/json-comments-rs/actions) |
| 4 | [](https://docs.rs/json_comments/) |
| 5 | |
| 6 | `json_comments` is a library to strip out comments from JSON-like text. By processing text |
| 7 | through a [`StripComments`] adapter first, it is possible to use a standard JSON parser (such |
| 8 | as [serde\_json](https://crates.io/crates/serde_json) with quasi-json input that contains |
| 9 | comments. |
| 10 | |
| 11 | In fact, this code makes few assumptions about the input and could probably be used to strip |
| 12 | comments out of other types of code as well, provided that strings use double quotes and |
| 13 | backslashes are used for escapes in strings. |
| 14 | |
| 15 | The following types of comments are supported: |
| 16 | - C style block comments (`/* ... */`) |
| 17 | - C style line comments (`// ...`) |
| 18 | - Shell style line comments (`# ...`) |
| 19 | |
| 20 | ## Example using serde\_json |
| 21 | |
| 22 | ```rust |
| 23 | use serde_json::{Result, Value}; |
| 24 | use json_comments::StripComments; |
| 25 | |
| 26 | fn main() -> Result<()> { |
| 27 | // Some JSON input data as a &str. Maybe this comes form the user. |
| 28 | let data = r#" |
| 29 | { |
| 30 | "name": /* full */ "John Doe", |
| 31 | "age": 43, |
| 32 | "phones": [ |
| 33 | "+44 1234567", // work phone |
| 34 | "+44 2345678" // home phone |
| 35 | ] |
| 36 | }"#; |
| 37 | |
| 38 | // Strip the comments from the input (use `as_bytes()` to get a `Read`). |
| 39 | let stripped = StripComments::new(data.as_bytes()); |
| 40 | // Parse the string of data into serde_json::Value. |
| 41 | let v: Value = serde_json::from_reader(stripped)?; |
| 42 | |
| 43 | println!("Please call {} at the number {}", v["name"], v["phones"][0]); |
| 44 | |
| 45 | Ok(()) |
| 46 | } |
| 47 | ``` |