Skip to main content

crate_cli/fmt/json/
fn.rs

1use super::*;
2
3/// Formats JSON (`.json`, `tsconfig.json`, `.vscode/*.json`) matching VS Code Prettier 3.7.4 `json` parser (`tabWidth: 2`, `printWidth: 80`, `objectWrap: "preserve"`, allows comments, strips trailing commas).
4///
5/// # Arguments
6///
7/// - `&str` - Raw JSON source text.
8///
9/// # Returns
10///
11/// - `Result<String, io::Error>` - Formatted JSON text, or an invalid-data I/O error on syntax failure.
12#[inline]
13pub fn format_json(input: &str) -> Result<String, io::Error> {
14    tidy::json::format(input, &VSCODE_JSON_OPTIONS)
15        .map_err(|_: tidy::Error| io::Error::new(ErrorKind::InvalidData, ERROR_JSON_PARSE_FAILED))
16}
17
18/// Formats JSON manifests (`package.json`, `package-lock.json`, `composer.json`) matching VS Code Prettier 3.7.4 `json-stringify` parser.
19///
20/// # Arguments
21///
22/// - `&str` - Raw JSON manifest text.
23///
24/// # Returns
25///
26/// - `Result<String, io::Error>` - Expanded JSON text, or an invalid-data I/O error on syntax failure.
27#[inline]
28pub fn format_json_stringify(input: &str) -> Result<String, io::Error> {
29    tidy::json::format(input, &VSCODE_JSON_STRINGIFY_OPTIONS)
30        .map_err(|_: tidy::Error| io::Error::new(ErrorKind::InvalidData, ERROR_JSON_PARSE_FAILED))
31}
32
33/// Formats JSONC (`.jsonc`, `.cjson`) matching VS Code Prettier 3.7.4 `jsonc` parser (preserving comments and `trailingComma: "all"`).
34///
35/// # Arguments
36///
37/// - `&str` - Raw JSONC source text.
38///
39/// # Returns
40///
41/// - `String` - Formatted JSONC text, or unchanged input if syntax errors occur.
42#[inline]
43pub fn format_jsonc(input: &str) -> String {
44    tidy::json::format(input, &VSCODE_JSONC_OPTIONS)
45        .unwrap_or_else(|_: tidy::Error| input.to_string())
46}