How to strip out comments from JSON in Rust

A tutorial on how to strip out comments from JSON in Rust

This is a tutorial in how you can remove comments from a JSON-like text in Rust, programmatically. This sanitizes your code and makes it easier to read while preserving formatting.

Here are the solutions:

(a). Use json-comments-rs

json_comments is a library to strip out comments from JSON-like text.

By processing text through a [StripComments] adapter first, it is possible to use a standard JSON parser (such as serde_json with quasi-json input that contains comments.

Here are type ofcomments supported.

  • C style block comments (/* ... */)
  • C style line comments (// ...)
  • Shell style line comments (# ...)


The example uses serde_json

use serde_json::{Result, Value};
use json_comments::StripComments;

fn main() -> Result<()> {
// Some JSON input data as a &str. Maybe this comes form the user.
let data = r#"
        "name": /* full */ "John Doe",
        "age": 43,
        "phones": [
            "+44 1234567", // work phone
            "+44 2345678"  // home phone

// Strip the comments from the input (use as_bytes() to get a Read).
let stripped = StripComments::new(data.as_bytes());
// Parse the string of data into serde_json::Value.
let v: Value = serde_json::from_reader(stripped)?;

println!("Please call {} at the number {}", v["name"], v["phones"][0]);



Read more here.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *