pub fn load_json_file_and_strip_json_comments(path: std::path::PathBuf) -> String {
let json_string_with_comment = std::fs::read_to_string(path).expect("Failed to read JSON file");
strip_json_comments(&json_string_with_comment, true)
}
pub fn strip_json_comments(json_with_comments: &str, preserve_locations: bool) -> String {
let mut json_without_comments = String::with_capacity(json_with_comments.len());
let mut block_comment_depth: u8 = 0;
let mut is_in_string: bool = false;
for line in json_with_comments.split('\n') {
let mut last_char: Option<char> = None;
for cur_char in line.chars() {
if block_comment_depth == 0 && last_char != Some('\\') && cur_char == '"' {
is_in_string = !is_in_string;
}
if !is_in_string && last_char == Some('/') && cur_char == '/' {
last_char = None;
if preserve_locations {
json_without_comments.push_str(" ");
}
break; }
if !is_in_string && last_char == Some('/') && cur_char == '*' {
block_comment_depth += 1;
last_char = None;
if preserve_locations {
json_without_comments.push_str(" ");
}
} else if !is_in_string && last_char == Some('*') && cur_char == '/' {
if block_comment_depth > 0 {
block_comment_depth = block_comment_depth.saturating_sub(1);
}
last_char = None;
if preserve_locations {
json_without_comments.push_str(" ");
}
} else {
if block_comment_depth != 0 {
if preserve_locations {
json_without_comments.push(' ');
}
} else if let Some(last_char) = last_char {
json_without_comments.push(last_char);
}
last_char = Some(cur_char);
}
}
if let Some(last_char) = last_char {
if block_comment_depth == 0 {
json_without_comments.push(last_char);
} else if preserve_locations {
json_without_comments.push(' ');
}
}
while json_without_comments.ends_with(' ') {
json_without_comments.pop();
}
json_without_comments.push('\n');
}
json_without_comments
}