fixjson

repository·master·Indexed 41 days ago

https://github.com/rhysd/fixjson

A JSON fixer and formatter that converts relaxed JSON5 input into standard, pretty-printed JSON. It handles common human errors such as trailing commas, missing commas, single quotes, and unescaped newlines. Available as a CLI tool and a programmatic API via the FixJSON class and helper functions like fixString() and fixFile().

Tokens
1.5K
Snippets
8
Records
9
Agent score
51%

What's inside fixjson

  1. Use the fixjson CLI

    master

    The fixjson CLI reads input in relaxed JSON5 format and outputs valid, pretty-printed JSON.

    • If you provide file paths (including globs like dir/**/*.json), it processes those files.
    • If you provide a directory, it formats all JSON files within that directory.
    • If no path is provided, it reads from STDIN.

    Common use cases include fixing trailing commas, adding missing commas, quoting object keys, converting single quotes to double quotes, handling newlines in strings, and converting hex numbers to decimal.

    fixjson [--write|--indent|--minify|--stdin-filename] [paths...]
  2. Integrate fixjson with editors

    master

    The fixjson CLI is designed to be used with editor extensions for automatic formatting. Supported integrations include:

    • Vim: via vim-fixjson, ALE, neoformat, or vim-autoformat.
    • Other editors that can call CLI tools for formatting.
  3. Configure the FixJSON class

    master

    The FixJSON class accepts an optional Config object to control how JSON is parsed and written.

    Key configuration options:

    • write: If true, the tool will overwrite the original files. If false (default), it outputs the fixed JSON to stdout.
    • indent: Controls indentation. Can be a number (representing the number of spaces) or left undefined to use automatic detection via detect-indent.
    • minify: If true, the output will be minified (no indentation).
    • stdinFilename: A string used as the filename label when reading from stdin.
    • stdout: A NodeJS.WriteStream to redirect the output (defaults to process.stdout).
    export interface Config {
        write?: boolean;
        indent?: number;
        minify?: boolean;
        stdinFilename?: string;
        stdout?: NodeJS.WriteStream;
    }
  4. Reference the fixjson CLI options

    master

    The following flags are available for the fixjson command:

    • --write or -w: Overwrites the input files with the fixed JSON.
    • --indent {num} or -i {num}: Sets the indentation width. If this option is not provided, the tool automatically detects the indentation spaces.
    • --minify: Minifies the output JSON.
    • --stdin-filename: Used when reading from STDIN to specify the filename (useful for tools that rely on file extensions).
    • [paths...]: One or more file paths or globs to process.
    # Example: Overwrite files with detected indentation
    fixjson --write file.json
    
    # Example: Use a specific indentation width
    fixjson --indent 2 file.json
    
    # Example: Process all JSON files in a directory using a glob
    fixjson "dir/**/*.json"
  5. Fix a JSON file with fixFile()

    master

    The fixFile helper function provides a shorthand way to read a file, fix its JSON content, and return the result as a string. This is an asynchronous operation.

    import { fixFile } from './index';
    
    async function run() {
      const fixedContent = await fixFile('config.json', { indent: 2 });
      console.log(fixedContent);
    }
    run();
  6. Fix a JSON string with fixString()

    master

    The fixString helper function provides a shorthand way to fix a JSON string without manually instantiating the FixJSON class. It returns the formatted JSON string.

    import { fixString } from './index';
    
    const input = '{ name: "rhysd" }';
    const output = fixString(input, { indent: 4 });
    console.log(output);
  7. Use the FixJSON class

    master

    The FixJSON class is the primary entry point for programmatic JSON fixing. You can instantiate it with a Config object and use its methods to process strings, files, or multiple file patterns via main().

    • main(argv: string[]): Processes files provided in the argv array. If argv is empty, it reads from stdin and writes to stdout (or the configured stdout stream). Returns the number of files processed or 1 if reading from stdin.
    • convertString(input: string): Takes a raw JSON string (potentially malformed/relaxed) and returns a formatted JSON string.
    • convertFile(path: string): Reads a file from the given path and returns the fixed JSON content as a string.
    import FixJSON from './index';
    
    // Example: Processing a string
    const fixer = new FixJSON({ indent: 2 });
    const fixed = fixer.convertString('{\n  key: "value"
    }');
    
    // Example: Running the main loop with file patterns
    const instance = new FixJSON({ write: true });
    await instance.main(['src/**/*.json']);
  8. fixjson CLI options reference

    master

    The following options are available for the fixjson command line interface:

    -w, --write          Overwrite a file instead of outputting to stdout (boolean, default: false)
    --minify             Disable pretty print (boolean, default: false)
    -i, --indent         Indent of JSON output (number, default: undefined)
    --stdin-filename     Assuming a file name when reading from stdin (string, default: undefined)