### Basic CLI Usage Source: https://context7.com/rhysd/fixjson/llms.txt Commands for installing the tool and fixing JSON files via stdout or glob patterns. ```bash # Install globally npm install -g fixjson # Fix a single file and output to stdout fixjson config.json # Fix multiple files using glob pattern fixjson "src/**/*.json" # Read from stdin and output fixed JSON echo '{ foo: 42, bar: "test", }' | fixjson # Output: # { # "foo": 42, # "bar": "test" # } ``` -------------------------------- ### FixJSON Class Usage Source: https://context7.com/rhysd/fixjson/llms.txt Demonstrates how to instantiate and use the FixJSON class for converting JSON strings and files, with examples of default and custom configurations. ```APIDOC ## FixJSON Class The main class providing full control over JSON fixing operations. Use this when you need to process multiple files or customize behavior. ### Instantiate FixJSON ```javascript const FixJSON = require('fixjson').default; // Basic instantiation with default config const fixer = new FixJSON(); ``` ### Convert String ```javascript const result = fixer.convertString(`{ name: 'test' value: 0xff }`); console.log(result); // Output: // { // "name": "test", // "value": 255 // } ``` ### Convert File ```javascript // Convert a file (returns Promise) fixer.convertFile('./config.json').then(fixed => { console.log(fixed); }); ``` ### Configuration Options ```javascript // With configuration options const minifier = new FixJSON({ minify: true }); console.log(minifier.convertString('{ foo: 1, bar: 2 }')); // Output: {"foo":1,"bar":2} const indenter = new FixJSON({ indent: 4 }); console.log(indenter.convertString('{foo:1}')); // Output: // { // "foo": 1 // } ``` ### Batch Processing ```javascript async function batchProcess() { const fixer = new FixJSON(); const files = ['a.json', 'b.json', 'c.json']; for (const file of files) { try { const fixed = await fixer.convertFile(file); console.log(`${file}:`, fixed); } catch (err) { console.error(`Error in ${file}:`, err.message); } } } ``` ### Fix In-Place ```javascript // Fix files and write in-place async function fixInPlace() { const fixer = new FixJSON({ write: true }); const numFixed = await fixer.main(['src/**/*.json']); console.log(`Fixed ${numFixed} files`); } ``` ### Custom Stdout ```javascript // Custom stdout for capturing output const { Writable } = require('stream'); const chunks = []; const capture = new Writable({ write(chunk, encoding, callback) { chunks.push(chunk); callback(); } }); const customFixer = new FixJSON({ stdout: capture }); customFixer.main(['config.json']).then(() => { const output = Buffer.concat(chunks).toString(); console.log('Captured:', output); }); ``` ``` -------------------------------- ### CLI Usage - Basic Command Source: https://context7.com/rhysd/fixjson/llms.txt Installs and uses the fixjson CLI to format JSON files. It can read from files, directories, glob patterns, or stdin, and outputs the fixed JSON to stdout. ```APIDOC ## CLI Usage - Basic Command ### Description Installs and uses the `fixjson` CLI to format JSON files. It can read from files, directories, glob patterns, or stdin, and outputs the fixed JSON to stdout. ### Method N/A (CLI command) ### Endpoint N/A (CLI command) ### Parameters N/A ### Request Example ```bash # Install globally npm install -g fixjson # Fix a single file and output to stdout fixjson config.json # Fix multiple files using glob pattern fixjson "src/**/*.json" # Read from stdin and output fixed JSON echo '{ foo: 42, bar: "test", }' | fixjson ``` ### Response #### Success Response (stdout) - **output** (string) - Properly formatted JSON string. ### Response Example ```json { "foo": 42, "bar": "test" } ``` ``` -------------------------------- ### Install fixjson Globally Source: https://github.com/rhysd/fixjson/blob/master/README.md Install the fixjson CLI tool globally using npm. This makes the `fixjson` command available in your terminal. ```sh npm install -g fixjson ``` -------------------------------- ### Apply Multiple FixJSON Configuration Options Source: https://context7.com/rhysd/fixjson/llms.txt Illustrates creating FixJSON instances with various configuration combinations, such as indentation and minification. Also shows how to access the current configuration. ```javascript const FixJSON = require('fixjson').default; // Example: Custom configuration combinations const configs = [ { indent: 2 }, // 2-space indent { indent: 4 }, // 4-space indent { minify: true }, // Minified output { write: true }, // Overwrite files { stdinFilename: 'input.json' }, // Custom stdin filename ]; // Create fixer with specific config const fixer = new FixJSON({ indent: 2, minify: false }); // Access config after creation console.log(fixer.config); // Output: { write: false, minify: false, indent: 2, stdout: [WriteStream] } ``` -------------------------------- ### Instantiate and Convert JSON String with FixJSON Source: https://context7.com/rhysd/fixjson/llms.txt Demonstrates basic instantiation of the FixJSON class and converting a JSON string. Handles unquoted keys and hex numbers. ```javascript const FixJSON = require('fixjson').default; // Basic instantiation with default config const fixer = new FixJSON(); // Convert a string directly const result = fixer.convertString(`{ name: 'test' value: 0xff }`); console.log(result); // Output: // { // "name": "test", // "value": 255 // } ``` -------------------------------- ### CLI Usage - Write to File (--write, -w) Source: https://context7.com/rhysd/fixjson/llms.txt Uses the `--write` or `-w` flag to overwrite files in-place with the fixed JSON content. ```APIDOC ## CLI Usage - Write to File (--write, -w) ### Description Uses the `--write` or `-w` flag to overwrite files in-place with the fixed JSON content. ### Method N/A (CLI command) ### Endpoint N/A (CLI command) ### Parameters #### Query Parameters - **--write, -w** (boolean) - Required/Optional - Overwrite files in-place. ### Request Example ```bash # Fix and overwrite a single file fixjson --write config.json # Fix all JSON files in a directory recursively fixjson -w src/ # Fix multiple files with glob pattern fixjson -w "**/*.json" ``` ### Response #### Success Response (stdout) - **message** (string) - Confirmation message, e.g., "formatted 15 file(s)". ### Response Example ``` formatted 15 file(s) ``` ``` -------------------------------- ### Overwrite Files with CLI Source: https://context7.com/rhysd/fixjson/llms.txt Use the --write or -w flag to modify files in-place. ```bash # Fix and overwrite a single file fixjson --write config.json # Fix all JSON files in a directory recursively fixjson -w src/ # Fix multiple files with glob pattern fixjson -w "**/*.json" # Output: formatted 15 file(s) ``` -------------------------------- ### Basic fixjson Usage Source: https://github.com/rhysd/fixjson/blob/master/README.md Run the `fixjson` command with optional paths to format JSON files. If no paths are provided, it reads from standard input. Use `--write` to overwrite files in place. ```sh fixjson [--write|--indent|--minify|--stdin-filename] [paths...] ``` -------------------------------- ### Configure Indentation with CLI Source: https://context7.com/rhysd/fixjson/llms.txt Specify custom indentation width using the --indent or -i flag. ```bash # Force 4-space indentation fixjson --indent 4 config.json # Force 2-space indentation fixjson -i 2 config.json # Input: {foo:42,bar:"test"} # Output with -i 4: # { # "foo": 42, # "bar": "test" # } ``` -------------------------------- ### Instantiate FixJSON with Minify Option Source: https://context7.com/rhysd/fixjson/llms.txt Creates a FixJSON instance configured for minified output. Useful for reducing file size. ```javascript // With configuration options const minifier = new FixJSON({ minify: true }); console.log(minifier.convertString('{ foo: 1, bar: 2 }')); // Output: {"foo":1,"bar":2} ``` -------------------------------- ### Convert JSON File with FixJSON Source: https://context7.com/rhysd/fixjson/llms.txt Shows how to use FixJSON to convert a JSON file. This method returns a Promise. ```javascript // Convert a file (returns Promise) fixer.convertFile('./config.json').then(fixed => { console.log(fixed); }); ``` -------------------------------- ### Config Interface Source: https://context7.com/rhysd/fixjson/llms.txt Details the configuration options available for customizing FixJSON behavior. ```APIDOC ### Config Interface Configuration options available for all API methods. ```typescript interface Config { write?: boolean; // Overwrite files instead of stdout (default: false) indent?: number; // Number of spaces for indentation (auto-detect if not set) minify?: boolean; // Output minified JSON (default: false) stdinFilename?: string; // Filename to use in errors when reading stdin stdout?: NodeJS.WriteStream; // Custom output stream (default: process.stdout) } ``` ### Example Configurations ```javascript const FixJSON = require('fixjson').default; // Example: Custom configuration combinations const configs = [ { indent: 2 }, // 2-space indent { indent: 4 }, // 4-space indent { minify: true }, // Minified output { write: true }, // Overwrite files { stdinFilename: 'input.json' }, // Custom stdin filename ]; // Create fixer with specific config const fixer = new FixJSON({ indent: 2, minify: false }); // Access config after creation console.log(fixer.config); // Output: { write: false, minify: false, indent: 2, stdout: [WriteStream] } ``` ``` -------------------------------- ### CLI Usage - Minify (--minify) Source: https://context7.com/rhysd/fixjson/llms.txt Disables pretty printing and outputs minified JSON using the `--minify` flag. ```APIDOC ## CLI Usage - Minify (--minify) ### Description Disables pretty printing and outputs minified JSON using the `--minify` flag. ### Method N/A (CLI command) ### Endpoint N/A (CLI command) ### Parameters #### Query Parameters - **--minify** (boolean) - Required/Optional - Output minified JSON without pretty printing. ### Request Example ```bash # Minify JSON output fixjson --minify config.json # Combine with write to minify files in-place fixjson --minify --write "dist/**/*.json" ``` ### Response #### Success Response (stdout) - **output** (string) - Minified JSON string. ### Response Example ```json {"foo":42,"bar":"test"} ``` ``` -------------------------------- ### Instantiate FixJSON with Indent Option Source: https://context7.com/rhysd/fixjson/llms.txt Creates a FixJSON instance configured for specific indentation. Useful for pretty-printing JSON. ```javascript const indenter = new FixJSON({ indent: 4 }); console.log(indenter.convertString('{foo:1}')); // Output: // { // "foo": 1 // } ``` -------------------------------- ### Batch Process Multiple JSON Files with FixJSON Source: https://context7.com/rhysd/fixjson/llms.txt An asynchronous function demonstrating how to process multiple JSON files in a loop using FixJSON. Includes error handling for individual files. ```javascript // Process multiple files async function batchProcess() { const fixer = new FixJSON(); const files = ['a.json', 'b.json', 'c.json']; for (const file of files) { try { const fixed = await fixer.convertFile(file); console.log(`${file}:`, fixed); } catch (err) { console.error(`Error in ${file}:`, err.message); } } } ``` -------------------------------- ### Minify JSON with CLI Source: https://context7.com/rhysd/fixjson/llms.txt Disable pretty printing to output minified JSON. ```bash # Minify JSON output fixjson --minify config.json # Input: # { # "foo": 42, # "bar": "test" # } # Output: {"foo":42,"bar":"test"} # Combine with write to minify files in-place fixjson --minify --write "dist/**/*.json" ``` -------------------------------- ### Specify Stdin Filename Source: https://context7.com/rhysd/fixjson/llms.txt Provide a filename for stdin input to ensure error messages are descriptive. ```bash # Specify filename for better error messages cat broken.json | fixjson --stdin-filename broken.json # If parsing fails, error will reference the filename: # Error: broken.json: Unexpected token 'x' at 3:5 ``` -------------------------------- ### JSON5 Relaxed Syntax Support Source: https://context7.com/rhysd/fixjson/llms.txt Illustrates how FixJSON handles and corrects common JSON5 syntax errors, making it more forgiving for human editing. ```APIDOC ## JSON5 Relaxed Syntax Support Fixjson accepts a relaxed JSON5 syntax that's more forgiving for human editing. Here's a comprehensive example showing all supported features. ### Example of Relaxed JSON5 Input ```javascript const { fixString } = require('fixjson'); // All these "broken" JSON formats are fixed automatically const relaxedInput = `{ // Comments are stripped (JSON5 feature) name: "project", // Unquoted keys version: '1.0.0', // Single quotes -> double quotes count: 0xff, // Hex numbers -> decimal items: [ "one" "two" // Missing commas between elements "three" ], nested: { foo: 1, bar: 2, // Trailing comma in object }, description: "A multi-line description that spans multiple lines", // Newlines in strings -> \n escapes }`; const fixed = fixString(relaxedInput); console.log(fixed); // Output: // { // "name": "project", // "version": "1.0.0", // "count": 255, // "items": [ // "one", // "two", // "three" // ], // "nested": { // "foo": 1, // "bar": 2 // }, // "description": "A multi-line\ndescription that spans\nmultiple lines" // } ``` ``` -------------------------------- ### CLI Usage - Stdin Filename (--stdin-filename) Source: https://context7.com/rhysd/fixjson/llms.txt Specifies a filename when reading from stdin using `--stdin-filename`. This is useful for editor integrations to provide more accurate error messages. ```APIDOC ## CLI Usage - Stdin Filename (--stdin-filename) ### Description Specifies a filename when reading from stdin using `--stdin-filename`. This is useful for editor integrations to provide more accurate error messages. ### Method N/A (CLI command) ### Endpoint N/A (CLI command) ### Parameters #### Query Parameters - **--stdin-filename** (string) - Required/Optional - Specify a filename for input read from stdin. ### Request Example ```bash # Specify filename for better error messages cat broken.json | fixjson --stdin-filename broken.json ``` ### Response #### Error Response Example ``` Error: broken.json: Unexpected token 'x' at 3:5 ``` ``` -------------------------------- ### Programmatic File Fixing Source: https://context7.com/rhysd/fixjson/llms.txt Use fixFile to process files asynchronously. ```javascript const { fixFile } = require('fixjson'); // Fix a single file async function processConfig() { try { const fixed = await fixFile('./config.json'); console.log(fixed); } catch (err) { console.error('Failed to fix:', err.message); } } // Fix with custom indent async function fixWithIndent() { const fixed = await fixFile('./data.json', { indent: 2 }); return fixed; } // Process and save fixed JSON const fs = require('fs').promises; async function fixAndSave(inputPath, outputPath) { const fixed = await fixFile(inputPath); await fs.writeFile(outputPath, fixed); console.log(`Fixed ${inputPath} -> ${outputPath}`); } fixAndSave('./input.json', './output.json'); ``` -------------------------------- ### Capture FixJSON Output to a Custom Stream Source: https://context7.com/rhysd/fixjson/llms.txt Shows how to redirect FixJSON's standard output to a custom stream for capturing results programmatically. Requires Node.js 'stream' module. ```javascript // Custom stdout for capturing output const { Writable } = require('stream'); const chunks = []; const capture = new Writable({ write(chunk, encoding, callback) { chunks.push(chunk); callback(); } }); const customFixer = new FixJSON({ stdout: capture }); customFixer.main(['config.json']).then(() => { const output = Buffer.concat(chunks).toString(); console.log('Captured:', output); }); ``` -------------------------------- ### Fix JSON Files In-Place with FixJSON Source: https://context7.com/rhysd/fixjson/llms.txt Demonstrates using FixJSON with the 'write: true' option to modify JSON files directly. Returns the count of fixed files. ```javascript // Fix files and write in-place async function fixInPlace() { const fixer = new FixJSON({ write: true }); const numFixed = await fixer.main(['src/**/*.json']); console.log(`Fixed ${numFixed} files`); } ``` -------------------------------- ### Programmatic API - fixFile Source: https://context7.com/rhysd/fixjson/llms.txt Fixes a JSON5 file and returns the corrected JSON as a string. This method returns a Promise. ```APIDOC ## Programmatic API - fixFile ### Description Fixes a JSON5 file and returns the corrected JSON as a string. This method returns a Promise. ### Method `fixFile(path, config?)` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the JSON5 file to fix. - **config** (object) - Optional - Configuration object. - **indent** (number) - Optional - Specify the number of spaces for indentation. - **minify** (boolean) - Optional - Output minified JSON without pretty printing. ### Request Example ```javascript const { fixFile } = require('fixjson'); // Fix a single file async function processConfig() { try { const fixed = await fixFile('./config.json'); console.log(fixed); } catch (err) { console.error('Failed to fix:', err.message); } } // Fix with custom indent async function fixWithIndent() { const fixed = await fixFile('./data.json', { indent: 2 }); return fixed; } // Process and save fixed JSON const fs = require('fs').promises; async function fixAndSave(inputPath, outputPath) { const fixed = await fixFile(inputPath); await fs.writeFile(outputPath, fixed); console.log(`Fixed ${inputPath} -> ${outputPath}`); } fixAndSave('./input.json', './output.json'); ``` ### Response #### Success Response (200) - **output** (string) - The fixed and formatted JSON string from the file. #### Error Response - **message** (string) - Error message if the file cannot be fixed or read. ``` -------------------------------- ### CLI Usage - Custom Indentation (--indent, -i) Source: https://context7.com/rhysd/fixjson/llms.txt Specifies the indentation width for the output JSON using the `--indent` or `-i` option. If not provided, Fixjson auto-detects existing indentation. ```APIDOC ## CLI Usage - Custom Indentation (--indent, -i) ### Description Specifies the indentation width for the output JSON using the `--indent` or `-i` option. If not provided, Fixjson auto-detects existing indentation. ### Method N/A (CLI command) ### Endpoint N/A (CLI command) ### Parameters #### Query Parameters - **--indent, -i** (number) - Required/Optional - Specify the number of spaces for indentation. ### Request Example ```bash # Force 4-space indentation fixjson --indent 4 config.json # Force 2-space indentation fixjson -i 2 config.json ``` ### Response #### Success Response (stdout) - **output** (string) - Properly formatted JSON string with specified indentation. ### Response Example ```json { "foo": 42, "bar": "test" } ``` ``` -------------------------------- ### FixJSON Configuration Interface Source: https://context7.com/rhysd/fixjson/llms.txt Defines the TypeScript interface for FixJSON configuration options, including write, indent, minify, stdinFilename, and stdout. ```typescript interface Config { write?: boolean; // Overwrite files instead of stdout (default: false) indent?: number; // Number of spaces for indentation (auto-detect if not set) minify?: boolean; // Output minified JSON (default: false) stdinFilename?: string; // Filename to use in errors when reading stdin stdout?: NodeJS.WriteStream; // Custom output stream (default: process.stdout) } ``` -------------------------------- ### Fix Relaxed JSON5 Syntax with fixString Source: https://context7.com/rhysd/fixjson/llms.txt Demonstrates the `fixString` function's ability to correct various JSON5 syntax issues, including comments, unquoted keys, single quotes, hex numbers, missing commas, trailing commas, and newlines within strings. ```javascript const { fixString } = require('fixjson'); // All these "broken" JSON formats are fixed automatically const relaxedInput = `{ // Comments are stripped (JSON5 feature) name: "project", // Unquoted keys version: '1.0.0', // Single quotes -> double quotes count: 0xff, // Hex numbers -> decimal items: [ "one" "two" // Missing commas between elements "three" ], nested: { foo: 1, bar: 2, // Trailing comma in object }, description: "A multi-line description that spans multiple lines", // Newlines in strings -> \n escapes }`; const fixed = fixString(relaxedInput); console.log(fixed); // Output: // { // "name": "project", // "version": "1.0.0", // "count": 255, // "items": [ // "one", // "two", // "three" // ], // "nested": { // "foo": 1, // "bar": 2 // }, // "description": "A multi-line\ndescription that spans\nmultiple lines" // } ``` -------------------------------- ### Programmatic API - fixString Source: https://context7.com/rhysd/fixjson/llms.txt Fixes a JSON5 string and returns the corrected JSON as a string. This is the simplest way to use Fixjson programmatically. ```APIDOC ## Programmatic API - fixString ### Description Fixes a JSON5 string and returns the corrected JSON as a string. This is the simplest way to use Fixjson programmatically. ### Method `fixString(input, config?)` ### Parameters #### Path Parameters - **input** (string) - Required - The JSON5 string to fix. - **config** (object) - Optional - Configuration object. - **indent** (number) - Optional - Specify the number of spaces for indentation. - **minify** (boolean) - Optional - Output minified JSON without pretty printing. ### Request Example ```javascript const { fixString } = require('fixjson'); // Fix trailing commas const input1 = `{ "name": "test", "items": [1, 2, 3,], }`; console.log(fixString(input1)); // Fix missing commas between elements const input2 = `{ "foo": 42 "bar": "test" "baz": [1 2 3] }`; console.log(fixString(input2)); // Fix unquoted keys and single quotes const input3 = `{foo: 42, bar: 'hello'}`; console.log(fixString(input3)); // Convert hex numbers to decimal const hexInput = `{ value: 0xdeadbeef }`; console.log(fixString(hexInput)); // Fix newlines in strings const multilineInput = `{ "message": "Hello World" }`; console.log(fixString(multilineInput)); // With custom configuration console.log(fixString('{foo: 1}', { indent: 4 })); console.log(fixString('{foo: 1, bar: 2}', { minify: true })); ``` ### Response #### Success Response (200) - **output** (string) - The fixed and formatted JSON string. ### Response Example ```json { "name": "test", "items": [ 1, 2, 3 ] } ``` ``` -------------------------------- ### Programmatic String Fixing Source: https://context7.com/rhysd/fixjson/llms.txt Use fixString to process JSON5 strings into valid JSON. ```javascript const { fixString } = require('fixjson'); // Fix trailing commas const input1 = `{ "name": "test", "items": [1, 2, 3,], }`; console.log(fixString(input1)); // Output: // { // "name": "test", // "items": [ // 1, // 2, // 3 // ] // } // Fix missing commas between elements const input2 = `{ "foo": 42 "bar": "test" "baz": [1 2 3] }`; console.log(fixString(input2)); // Output: // { // "foo": 42, // "bar": "test", // "baz": [ // 1, // 2, // 3 // ] // } // Fix unquoted keys and single quotes const input3 = `{foo: 42, bar: 'hello'}`; console.log(fixString(input3)); // Output: // { // "foo": 42, // "bar": "hello" // } // Convert hex numbers to decimal const hexInput = `{ value: 0xdeadbeef }`; console.log(fixString(hexInput)); // Output: // { // "value": 3735928559 // } // Fix newlines in strings const multilineInput = `{ "message": "Hello World" }`; console.log(fixString(multilineInput)); // Output: // { // "message": "Hello\nWorld" // } // With custom configuration console.log(fixString('{foo: 1}', { indent: 4 })); // Output: // { // "foo": 1 // } console.log(fixString('{foo: 1, bar: 2}', { minify: true })); // Output: {"foo":1,"bar":2} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.