### ESLint Configuration with Recommended JSON Preset Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/plugin.md This example demonstrates using the recommended configuration preset from the @eslint/json plugin. It simplifies setup by enabling a predefined set of recommended rules for JSON files. ```javascript import { defineConfig } from "eslint/config"; import json from "@eslint/json"; export default defineConfig([ { files: ["**/*.json"], language: "json/json", plugins: { json }, extends: ["json/recommended"], }, ]); ``` -------------------------------- ### Example sort-keys Rule Configuration Source: https://github.com/eslint/json/blob/main/_autodocs/configuration.md Provides a concrete example of configuring the `json/sort-keys` rule with specific options for case-insensitive natural sorting of at least 3 keys. ```javascript "json/sort-keys": ["error", "asc", { caseSensitive: false, natural: true, minKeys: 3 }] ``` -------------------------------- ### Install ESLint JSON Plugin with bun Source: https://github.com/eslint/json/blob/main/README.md Install the ESLint JSON plugin as a development dependency using bun. This is a fast, all-in-one JavaScript runtime. ```shell bun add @eslint/json -D ``` -------------------------------- ### Example: Implementing a JSON Rule Visitor Source: https://github.com/eslint/json/blob/main/_autodocs/types.md Provides a concrete example of creating an ESLint rule for JSON. It demonstrates how to use visitor methods like Object, Object:exit, Member, and String to inspect the AST. ```javascript const rule = { create(context) { return { Object(node) { console.log("Entering object"); }, "Object:exit"(node) { console.log("Exiting object"); }, Member(node, parent) { console.log(`Member in object: ${node.name.value}`); }, String(node) { console.log(`String value: ${node.value}`); }, }; }, }; ``` -------------------------------- ### Install @eslint/json Plugin Source: https://github.com/eslint/json/blob/main/_autodocs/index.md Install the @eslint/json plugin as a development dependency using npm. ```bash npm install @eslint/json -D ``` -------------------------------- ### Example: No Empty Keys Rule Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/rules.md This example demonstrates the 'no-empty-keys' rule, which flags the use of empty strings as keys in JSON objects. ```json { "": "value", "name": "test" } // error: Empty key found. ``` -------------------------------- ### Default Options Example Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/custom-rules.md Demonstrates how to set default option values for a custom rule using the `defaultOptions` property in the meta object. ```javascript defaultOptions: [{ form: "NFC", caseSensitive: true }] ``` -------------------------------- ### Basic ESLint Configuration with JSON Plugin Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/plugin.md This example shows how to integrate the @eslint/json plugin into your ESLint configuration. It sets up the plugin and specifies rules for JSON files. ```javascript import { defineConfig } from "eslint/config"; import json from "@eslint/json"; export default defineConfig([ { plugins: { json }, }, { files: ["**/*.json"], language: "json/json", rules: { "json/no-duplicate-keys": "error", }, }, ]); ``` -------------------------------- ### ESLint JSON Module Import Examples Source: https://github.com/eslint/json/blob/main/_autodocs/modules.md Demonstrates how to import the ESLint JSON module using both ES module syntax and CommonJS. ```javascript // ES modules import json from "@eslint/json"; ``` ```javascript // CommonJS const json = require("@eslint/json").default; ``` -------------------------------- ### Example: No Duplicate Keys Rule Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/rules.md This example demonstrates the 'no-duplicate-keys' rule, which flags duplicate keys in JSON objects. ```json { "name": "value1", "name": "value2" } // error: Duplicate key "name" found. ``` -------------------------------- ### Schema Object Example Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/custom-rules.md Provides an example of a JSON schema used to validate rule options, ensuring that provided options conform to the expected structure and types. ```javascript schema: [ { type: "object", properties: { form: { enum: ["NFC", "NFD", "NKFC", "NFKD"], }, caseSensitive: { type: "boolean", }, }, additionalProperties: false, }, ] ``` -------------------------------- ### Example: Configuring Trailing Commas Source: https://github.com/eslint/json/blob/main/_autodocs/types.md Demonstrates how to enable trailing commas for JSONC files using languageOptions. This is useful for configurations that follow JSONC syntax. ```javascript export default defineConfig([ { files: ["**/tsconfig.json"], language: "json/jsonc", languageOptions: { allowTrailingCommas: true, }, }, ]); ``` -------------------------------- ### Install ESLint JSON Plugin for Deno Source: https://github.com/eslint/json/blob/main/README.md Add the ESLint JSON plugin for use within the Deno runtime environment. ```shell deno add @eslint/json ``` -------------------------------- ### Install ESLint JSON Plugin with yarn Source: https://github.com/eslint/json/blob/main/README.md Install the ESLint JSON plugin as a development dependency using yarn. This is an alternative package manager for Node.js environments. ```shell yarn add @eslint/json -D ``` -------------------------------- ### Example JSON Rule Implementation Source: https://github.com/eslint/json/blob/main/_autodocs/types.md An example of a JSON rule that disallows strings longer than a specified maximum length. It demonstrates how to define metadata, messages, schema, and implement the rule logic within the `create` function. ```typescript const rule: JSONRuleDefinition<{ RuleOptions: [{ maxLength: number }]; MessageIds: "stringTooLong"; }> = { meta: { type: "suggestion", languages: ["json/json", "json/jsonc", "json/json5"], docs: { recommended: false, description: "Disallow overly long strings", dialects: ["JSON", "JSONC", "JSON5"], url: "https://example.com/my-rule", }, messages: { stringTooLong: "String exceeds max length of {{max}}", }, schema: [ { type: "object", properties: { maxLength: { type: "integer", minimum: 1 }, }, }, ], defaultOptions: [{ maxLength: 100 }], }, create(context) { const [{ maxLength }] = context.options; return { String(node) { if (node.value.length > maxLength) { context.report({ node, messageId: "stringTooLong", data: { max: maxLength }, }); } }, }; }, }; ``` -------------------------------- ### Valid top-level JSON examples Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/rules.md Illustrates valid JSON structures that comply with the 'top-level-interop' rule, including empty and populated objects/arrays. ```json {} [] { "key": "value" } [1, 2, 3] ``` -------------------------------- ### Sort keys example (ascending, case-sensitive) Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/rules.md Demonstrates an object with unsorted keys that violates the default 'sort-keys' rule. ```json { "zebra": 1, "apple": 2 } // error: Expected object keys to be in ascending case-sensitive alphanumeric order. ``` -------------------------------- ### Install ESLint JSON Plugin with pnpm Source: https://github.com/eslint/json/blob/main/README.md Install the ESLint JSON plugin as a development dependency using pnpm. This is another package manager option for Node.js environments. ```shell pnpm install @eslint/json -D ``` -------------------------------- ### Recommended ESLint Configuration for JSON Files (CommonJS) Source: https://github.com/eslint/json/blob/main/README.md Apply the recommended ESLint configuration for JSON files using the new configuration system. This example uses CommonJS modules and extends the plugin's recommended rules. ```javascript // eslint.config.js const { defineConfig } = require("eslint/config"); const json = require("@eslint/json").default; module.exports = defineConfig([ // lint JSON files { files: ["**/*.json"], ignores: ["package-lock.json"], plugins: { json }, language: "json/json", extends: ["json/recommended"], }, // lint JSONC files { files: ["**/*.jsonc"], plugins: { json }, language: "json/jsonc", extends: ["json/recommended"], }, // lint JSON5 files { files: ["**/*.json5"], plugins: { json }, language: "json/json5", extends: ["json/recommended"], }, ]); ``` -------------------------------- ### Recommended ESLint Configuration for JSON Files (ESM) Source: https://github.com/eslint/json/blob/main/README.md Apply the recommended ESLint configuration for JSON files using the new configuration system. This example uses ECMAScript Modules (ESM) and extends the plugin's recommended rules. ```javascript // eslint.config.js import { defineConfig } from "eslint/config"; import json from "@eslint/json"; export default defineConfig([ // lint JSON files { files: ["**/*.json"], ignores: ["package-lock.json"], plugins: { json }, language: "json/json", extends: ["json/recommended"], }, // lint JSONC files { files: ["**/*.jsonc"], plugins: { json }, language: "json/jsonc", extends: ["json/recommended"], }, // lint JSON5 files { files: ["**/*.json5"], plugins: { json }, language: "json/json5", extends: ["json/recommended"], }, ]); ``` -------------------------------- ### Rule Languages Example Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/custom-rules.md Illustrates how to specify the language variants supported by a custom rule using the `languages` property in the meta object. ```javascript languages: ["json/json", "json/jsonc", "json/json5"] // All variants ``` -------------------------------- ### JetBrains WebStorm ESLint Scope Configuration Source: https://github.com/eslint/json/blob/main/README.md Example configuration for JetBrains WebStorm to include JSON, JSONC, and JSON5 files within the ESLint scope. ```text **/*.{js,ts,jsx,tsx,cjs,cts,mjs,mts,html,vue,json,jsonc,json5} ``` -------------------------------- ### CommonJS ESLint Flat Configuration Setup Source: https://github.com/eslint/json/blob/main/_autodocs/configuration.md Configure the @eslint/json plugin using CommonJS syntax with ESLint's flat configuration system. This is an alternative to the ES module import method. ```javascript const { defineConfig } = require("eslint/config"); const json = require("@eslint/json").default; module.exports = defineConfig([ { plugins: { json }, }, { files: ["**/*.json"], language: "json/json", rules: { "json/no-duplicate-keys": "error", }, }, ]); ``` -------------------------------- ### Directory Structure Overview Source: https://github.com/eslint/json/blob/main/_autodocs/DOCUMENTATION.md This markdown file outlines the directory structure of the @eslint/json documentation, showing the organization of API reference files, configuration guides, and type definitions. ```markdown output/ ├── README.md ← Overview and navigation ├── index.md ← Main technical reference entry ├── DOCUMENTATION.md ← This file ├── configuration.md ← All config options ├── types.md ← All type definitions ├── modules.md ← Module organization ├── MANIFEST.txt ← Generation manifest │ └── api-reference/ ├── plugin.md ← Plugin object ├── json-language.md ← JSONLanguage class ├── json-source-code.md ← JSONSourceCode class ├── rules.md ← All 6 rules ├── custom-rules.md ← Write custom rules └── utilities.md ← Helper functions ``` -------------------------------- ### Configure ESLint for JSON, JSONC, and JSON5 (CommonJS) Source: https://github.com/eslint/json/blob/main/README.md Configure ESLint to lint JSON, JSONC, and JSON5 files using the new configuration system. This example uses CommonJS modules. ```javascript // eslint.config.js const { defineConfig } = require("eslint/config"); const json = require("@eslint/json").default; module.exports = defineConfig([ { plugins: { json, }, }, // lint JSON files { files: ["**/*.json"], language: "json/json", rules: { "json/no-duplicate-keys": "error", }, }, // lint JSONC files { files: ["**/*.jsonc", ".vscode/*.json"], language: "json/jsonc", rules: { "json/no-duplicate-keys": "error", }, }, // lint JSON5 files { files: ["**/*.json5"], language: "json/json5", rules: { "json/no-duplicate-keys": "error", }, }, ]); ``` -------------------------------- ### Example: No Unnormalized Keys Rule Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/rules.md This example shows the 'no-unnormalized-keys' rule, which checks for non-normalized Unicode characters in JSON keys. The default normalization form is NFC. ```json { "café": "value" } // With form: "NFC" - checks if key uses NFC normalization ``` -------------------------------- ### Complete Custom Rule Example: No Long Descriptions Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/custom-rules.md A full example of a custom rule that prevents object members from having descriptions longer than a specified maximum length. It includes meta configuration, options schema, and visitor logic. ```javascript import { getRawKey } from "./util.js"; const rule = { meta: { type: "suggestion", languages: ["json/json", "json/jsonc", "json/json5"], docs: { recommended: false, description: "Disallow overly long key descriptions", dialects: ["JSON", "JSONC", "JSON5"], url: "https://example.com/rules/no-long-descriptions", }, messages: { descriptionTooLong: "Description exceeds {{max}} characters ({{actual}} found)", }, schema: [ { type: "object", properties: { maxLength: { type: "integer", minimum: 1, }, }, additionalProperties: false, }, ], defaultOptions: [{ maxLength: 100 }], }, create(context) { const [{ maxLength }] = context.options; return { Member(node) { const description = node.value; if ( description.type === "String" && description.value.length > maxLength ) { const rawKey = getRawKey(node, context.sourceCode); context.report({ loc: description.loc, messageId: "descriptionTooLong", data: { max: maxLength, actual: description.value.length, }, }); } }, }; }, }; export default rule; ``` -------------------------------- ### Example: Unsafe Values Rule Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/rules.md This example demonstrates the 'no-unsafe-values' rule, which detects potentially problematic numeric and string values in JSON, such as very large/small numbers or unpaired surrogates. ```json { "big": 9999999999999999999, "tiny": 1e-400, "text": "unpaired\uD800surrogate" } ``` -------------------------------- ### Top-level-interop rule violation example Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/rules.md Shows a JSON string that violates the 'top-level-interop' rule because it's a primitive string. ```json "just a string" // error: Top level item should be array or object, got 'String'. ``` -------------------------------- ### Allow Normalized JSON Keys (Default NFC) Source: https://github.com/eslint/json/blob/main/docs/rules/no-unnormalized-keys.md This example demonstrates correct JSON keys that adhere to the default NFC Unicode normalization form. ```jsonc /* eslint json/no-unnormalized-keys: "error" */ // Using NFC (default) normalized form { "café": "value" // é as a single code point } // All keys properly normalized { "résumé": "document", "naïve": "approach", "piñata": "party" } // ASCII-only keys are always normalized { "simple": "value", "no_special_chars": true } ``` -------------------------------- ### Fixable Rule Example Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/custom-rules.md Shows how to mark a rule as automatically fixable by setting the `fixable` property in the meta object. ```javascript fixable: "code" // Rule provides fix() function ``` -------------------------------- ### Correct JSON for allowLineSeparatedGroups Source: https://github.com/eslint/json/blob/main/docs/rules/sort-keys.md These examples show correct JSON formatting when `allowLineSeparatedGroups` is enabled. Blank lines are permitted between groups of sorted keys, aiding readability. ```jsonc /* eslint json/sort-keys: ["error", "asc", { allowLineSeparatedGroups: true }] */ { "b": 1, "a": 3 } ``` ```jsonc /* eslint json/sort-keys: ["error", "asc", { allowLineSeparatedGroups: true }] */ { "z": 3, // comment "b": 1, "c": 2 } ``` ```jsonc /* eslint json/sort-keys: ["error", "asc", { allowLineSeparatedGroups: true }] */ { "z": 3, // comment "b": 1, "c": 2 } ``` ```jsonc /* eslint json/sort-keys: ["error", "asc", { allowLineSeparatedGroups: true }] */ { "e": 1, "f": 2, "g": 3, "a": 4, "b": 5, "c": 6 } ``` ```jsonc /* eslint json/sort-keys: ["error", "asc", { allowLineSeparatedGroups: true }] */ { "c": 1, "d": 2, "e": 3 } ``` ```jsonc /* eslint json/sort-keys: ["error", "asc", { allowLineSeparatedGroups: true }] */ { "c": 1, "d": 2, // comment // comment "e": 4 } ``` ```jsonc /* eslint json/sort-keys: ["error", "asc", { allowLineSeparatedGroups: true }] */ { "b": 1 // comment before comma , "a": 2 } ``` ```jsonc /* eslint json/sort-keys: ["error", "asc", { allowLineSeparatedGroups: true }] */ { "b": 1, "a": 2, "c": 3 } ``` -------------------------------- ### Allow Normalized JSON Keys (NFD Form) Source: https://github.com/eslint/json/blob/main/docs/rules/no-unnormalized-keys.md This example demonstrates a correct JSON key when the rule is configured for the NFD normalization form. The key uses the decomposed representation of 'é'. ```jsonc /* eslint json/no-unnormalized-keys: ["error", { form: "NFD" }] */ { "cafe\u0301": "value", // é represented as 'e' + combining accent is valid in NFD } ``` -------------------------------- ### Configure ESLint for JSON, JSONC, and JSON5 (ESM) Source: https://github.com/eslint/json/blob/main/README.md Configure ESLint to lint JSON, JSONC, and JSON5 files using the new configuration system. This example uses ECMAScript Modules (ESM). ```javascript // eslint.config.js import { defineConfig } from "eslint/config"; import json from "@eslint/json"; export default defineConfig([ { plugins: { json, }, }, // lint JSON files { files: ["**/*.json"], language: "json/json", rules: { "json/no-duplicate-keys": "error", }, }, // lint JSONC files { files: ["**/*.jsonc", ".vscode/*.json"], language: "json/jsonc", rules: { "json/no-duplicate-keys": "error", }, }, // lint JSON5 files { files: ["**/*.json5"], language: "json/json5", rules: { "json/no-duplicate-keys": "error", }, }, ]); ``` -------------------------------- ### Get Inline Configuration Nodes Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/json-source-code.md Retrieves all comment tokens that match ESLint directive patterns, such as 'eslint', 'eslint-enable', 'eslint-disable', or 'eslint-disable-next-line'. Use this to find comments that might alter ESLint's behavior. ```javascript const configNodes = sourceCode.getInlineConfigNodes(); // Returns comments like: // /* eslint json/no-duplicate-keys: "error" */ // // eslint-disable-next-line json/no-empty-keys ``` -------------------------------- ### Valid JSON Objects with Unique Keys Source: https://github.com/eslint/json/blob/main/docs/rules/no-duplicate-keys.md These examples demonstrate correct JSON structures where all keys are unique. This includes simple objects, objects with multiple key-value pairs, empty objects, and nested objects where keys at different levels do not conflict. ```jsonc /* eslint json/no-duplicate-keys: "error" */ { "foo": 1, "bar": 2 } ``` ```jsonc { "foo": 1, "bar": 2, "baz": 3 } ``` ```jsonc // Empty objects are valid {} ``` ```jsonc // Nested objects with the same keys at different levels are valid { "foo": 1, "bar": { "bar": 2 } } ``` ```jsonc { "foo": { "bar": 5 }, "bar": 6 } ``` -------------------------------- ### Recommended Configuration Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/plugin.md The recommended configuration preset enables a set of rules that ESLint recommends for JSON files, including checks for duplicate keys, empty keys, unnormalized keys, and unsafe values. ```APIDOC ## Recommended Configuration ### Description This configuration preset enables a curated set of recommended rules for linting JSON files. It is designed to enforce best practices and catch common errors. ### Usage Extend the `json/recommended` configuration in your ESLint setup. ```javascript import { defineConfig } from "eslint/config"; import json from "@eslint/json"; export default defineConfig([ { files: ["**/*.json"], language: "json/json", plugins: { json }, extends: ["json/recommended"], }, ]); ``` ### Enabled Rules The `json/recommended` configuration enables the following rules: - `json/no-duplicate-keys` - `json/no-empty-keys` - `json/no-unnormalized-keys` - `json/no-unsafe-values` ``` -------------------------------- ### Create Function Visitor Methods Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/custom-rules.md Illustrates the structure of the `create` function, which returns a visitor object containing methods for traversing the Abstract Syntax Tree (AST) of JSON documents. ```javascript create(context) { return { // Visit methods Document(node) { }, Object(node) { }, String(node) { }, // ... etc // Exit methods "Object:exit"(node) { }, }; } ``` -------------------------------- ### Configure Rule with Options Source: https://github.com/eslint/json/blob/main/_autodocs/configuration.md Demonstrates how to configure an ESLint rule with options, passing an array where the first element is the severity and subsequent elements are rule-specific options. ```javascript rules: { "json/rule-name": ["error", option1, option2, ...] } ``` -------------------------------- ### getTokenAfter Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/json-source-code.md Gets the token immediately after the given node or token. It can optionally include comment tokens in the search. ```APIDOC ## getTokenAfter ### Description Gets the token immediately after the given node or token. It can optionally include comment tokens in the search. ### Method (Implicitly a method call on a SourceCode object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **nodeOrToken** (AnyNode | Token) - Required - The node or token to search from - **options** (object) - Optional - Search options - **options.includeComments** (boolean) - Optional - Whether to return comment tokens (defaults to `false`) ### Request Example ```javascript const nextToken = sourceCode.getTokenAfter(node); // With comments const next = sourceCode.getTokenAfter(node, { includeComments: true }); ``` ### Response #### Success Response (200) - **token** (Token | null) - The next token/comment, or `null` if none exists. #### Response Example (No explicit example provided in source, but implies returning a Token object or null) ``` -------------------------------- ### getTokenBefore Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/json-source-code.md Gets the token immediately before the given node or token. It can optionally include comment tokens in the search. ```APIDOC ## getTokenBefore ### Description Gets the token immediately before the given node or token. It can optionally include comment tokens in the search. ### Method (Implicitly a method call on a SourceCode object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **nodeOrToken** (AnyNode | Token) - Required - The node or token to search from - **options** (object) - Optional - Search options - **options.includeComments** (boolean) - Optional - Whether to return comment tokens (defaults to `false`) ### Request Example ```javascript const token = sourceCode.getTokenBefore(node); // Include comments const prevToken = sourceCode.getTokenBefore(node, { includeComments: true }); ``` ### Response #### Success Response (200) - **token** (Token | null) - The previous token/comment, or `null` if none exists. #### Response Example (No explicit example provided in source, but implies returning a Token object or null) ``` -------------------------------- ### Usage in no-duplicate-keys rule Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/utilities.md Demonstrates using `getKey` for comparison and `getRawKey` for user-friendly reporting in the `no-duplicate-keys` rule. ```javascript const key = getKey(node); // Normalized key const rawKey = getRawKey(node, context.sourceCode); // Report uses rawKey for user-friendly messages context.report({ messageId: "duplicateKey", data: { key: rawKey }, // "\"firstName\"" in error message }); ``` -------------------------------- ### Build ESLint JSON Project Source: https://github.com/eslint/json/blob/main/_autodocs/modules.md Command to initiate the build process for the ESLint JSON project. This command triggers several sub-tasks for generating code and documentation. ```bash npm run build ``` -------------------------------- ### Accessing Source Code Information Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/custom-rules.md Shows how to use `context.sourceCode` methods like `getText`, `getTokenBefore`, and `getTokenAfter` to retrieve information about nodes and tokens. ```javascript context.report({ node, messageId: "message", fix(fixer) { const text = context.sourceCode.getText(node); const before = context.sourceCode.getTokenBefore(node); const after = context.sourceCode.getTokenAfter(node); }, }); ``` -------------------------------- ### Plugin Recommended Configuration Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/plugin.md The 'configs.recommended' property provides a pre-configured set of rules for common JSON linting needs. It includes essential rules for ensuring JSON quality and consistency. ```javascript { name: "@eslint/json/recommended", plugins: { json: plugin }, rules: { "json/no-duplicate-keys": "error", "json/no-empty-keys": "error", "json/no-unnormalized-keys": "error", "json/no-unsafe-values": "error" } } ``` -------------------------------- ### Example of Valid JSONC with Trailing Commas Source: https://github.com/eslint/json/blob/main/_autodocs/configuration.md Demonstrates a valid JSONC object with trailing commas in its properties and array elements, enabled by the `allowTrailingCommas` option. ```jsonc { "name": "value", "items": [ 1, 2, 3, ], } ``` -------------------------------- ### ESLint JSON Package.json Configuration Source: https://github.com/eslint/json/blob/main/_autodocs/modules.md This configuration snippet from package.json shows how the main entry point and TypeScript types are defined, ensuring compatibility with both CommonJS and ES modules. ```json // package.json { "main": "dist/index.js", "types": "dist/index.d.ts", "exports": { ".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" } } } ``` -------------------------------- ### Instantiate JSONSourceCode Source: https://github.com/eslint/json/blob/main/_autodocs/modules.md Create an instance of JSONSourceCode to represent the source code, providing access to text, AST, and token management. ```javascript import { JSONSourceCode } from "@eslint/json"; const sourceCode = new JSONSourceCode({ text: code, ast: ast, }); ``` -------------------------------- ### Get Token After Node Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/json-source-code.md Retrieves the token immediately following a given node or token. Use the `includeComments` option to also search for following comment tokens. ```javascript const nextToken = sourceCode.getTokenAfter(node); // With comments const next = sourceCode.getTokenAfter(node, { includeComments: true }); ``` -------------------------------- ### Get Token Before Node Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/json-source-code.md Retrieves the token immediately preceding a given node or token. Use the `includeComments` option to also search for preceding comment tokens. ```javascript const token = sourceCode.getTokenBefore(node); // Include comments const prevToken = sourceCode.getTokenBefore(node, { includeComments: true }); ``` -------------------------------- ### Usage in Custom Rules Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/utilities.md Shows how to use `getKey` for logical checks and `getRawKey` for reporting issues in custom ESLint JSON rules. ```javascript const rule = { meta: { type: "problem", docs: { description: "My custom JSON rule", }, }, create(context) { return { Member(node) { const key = getKey(node); // Get normalized key for comparison const rawKey = getRawKey(node, context.sourceCode); // For reporting if (shouldReport(key)) { context.report({ loc: node.name.loc, message: `Invalid key: ${rawKey}`, }); } }, }; }, }; ``` -------------------------------- ### Plugin Rule Definitions Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/plugin.md The 'rules' property lists all available linting rules provided by the plugin. Each rule is mapped to its definition, allowing you to configure and apply them in your ESLint setup. ```javascript { "no-duplicate-keys": RuleDefinition, "no-empty-keys": RuleDefinition, "no-unnormalized-keys": RuleDefinition, "no-unsafe-values": RuleDefinition, "sort-keys": RuleDefinition, "top-level-interop": RuleDefinition } ``` -------------------------------- ### Accessing ESLint JSON Rules Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/rules.md Demonstrates how to import the @eslint/json plugin and access its individual rules programmatically. ```javascript import json from "@eslint/json"; // Access individual rules json.rules["no-duplicate-keys"] json.rules["no-empty-keys"] json.rules["no-unnormalized-keys"] json.rules["no-unsafe-values"] json.rules["sort-keys"] json.rules["top-level-interop"] ``` -------------------------------- ### Complete Custom Rule: Disallow Reserved Keys Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/custom-rules.md A full example of an ESLint rule that prevents the use of reserved keywords (like 'constructor', 'prototype') as object keys in JSON. ```javascript const RESERVED = new Set(["constructor", "prototype", "__proto__"]); const rule = { meta: { type: "problem", languages: ["json/json", "json/jsonc", "json/json5"], docs: { recommended: false, description: "Disallow reserved words as object keys", dialects: ["JSON", "JSONC", "JSON5"], url: "https://example.com/rules/no-reserved-keys", }, messages: { reserved: 'Reserved word "{{key}}" cannot be used as an object key', }, }, create(context) { return { Member(node) { const key = node.name.type === "String" ? node.name.value : node.name.name; if (RESERVED.has(key)) { context.report({ loc: node.name.loc, messageId: "reserved", data: { key }, }); } }, }; }, }; export default rule; ``` -------------------------------- ### Configuring ESLint JSON Rules Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/rules.md Shows how to configure the @eslint/json plugin and its rules within an ESLint flat configuration file. ```javascript import { defineConfig } from "eslint/config"; import json from "@eslint/json"; export default defineConfig([ { plugins: { json }, }, { files: ["**/*.json"], language: "json/json", rules: { "json/no-duplicate-keys": "error", "json/no-empty-keys": "error", "json/no-unnormalized-keys": ["error", { form: "NFC" }], "json/no-unsafe-values": "error", "json/sort-keys": ["error", "asc", { caseSensitive: true }], "json/top-level-interop": "warn", }, }, ]); ``` -------------------------------- ### Get Parent AST Node Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/json-source-code.md Retrieves the parent node of a given AST node. Returns undefined if the provided node is the root of the AST. Useful for navigating up the AST hierarchy. ```javascript const parent = sourceCode.getParent(memberNode); if (parent.type === "Object") { console.log("Member is in an object"); } ``` -------------------------------- ### Usage in sort-keys rule Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/utilities.md Illustrates using `getKey` for comparison logic and `getRawKey` for reporting in the `sort-keys` rule. ```javascript for (const member of node.members) { const thisName = getKey(member); // For comparison const thisRawName = getRawKey(member, sourceCode); // For messages if (!isValidOrder(prevName, thisName)) { context.report({ data: { thisName: thisRawName, prevName: prevRawName, }, }); } } ``` -------------------------------- ### Use Recommended ESLint Rules for JSON Source: https://github.com/eslint/json/blob/main/_autodocs/index.md Configure ESLint to extend the recommended rule set provided by the @eslint/json plugin for JSON files. ```javascript export default defineConfig([ { files: ["**/*.json"], language: "json/json", plugins: { json }, extends: ["json/recommended"], }, ]); ``` -------------------------------- ### Disallow Unnormalized JSON Keys (Default NFC) Source: https://github.com/eslint/json/blob/main/docs/rules/no-unnormalized-keys.md This example shows incorrect JSON keys that use decomposed forms or different representations of the same character, violating the default NFC normalization. ```jsonc /* eslint json/no-unnormalized-keys: "error" */ // Key using decomposed form (NFD) instead of composed form (NFC) { "cafe\u0301": "value" // é as 'e' + combining accent } // Different representations of the same visual character { "cafè": "espresso", "cafe\u0300": "latte" // same visual character in a different form } ``` -------------------------------- ### Utility Functions Source: https://github.com/eslint/json/blob/main/_autodocs/MANIFEST.txt Documentation for exported utility functions. ```APIDOC ## Functions ### `getKey()` - **Description**: Retrieves a key from a JSON structure. ### `getRawKey()` - **Description**: Retrieves the raw key from a JSON structure. ``` -------------------------------- ### Incorrect JSON for allowLineSeparatedGroups Source: https://github.com/eslint/json/blob/main/docs/rules/sort-keys.md These examples demonstrate incorrect JSON formatting when `allowLineSeparatedGroups` is set to `true`. The rule enforces sorting of keys, and this option allows for blank lines between groups of sorted keys. ```jsonc /* eslint json/sort-keys: ["error", "asc", { allowLineSeparatedGroups: true }] */ { "b": 1, "a": 3 } ``` ```jsonc /* eslint json/sort-keys: ["error", "asc", { allowLineSeparatedGroups: true }] */ { "z": 3, // comment "b": 1, "c": 2 } ``` ```jsonc /* eslint json/sort-keys: ["error", "asc", { allowLineSeparatedGroups: true }] */ { "b": 1 // comment before comma , "a": 2 } ``` ```jsonc /* eslint json/sort-keys: ["error", "asc", { allowLineSeparatedGroups: true }] */ { "e": 1, "f": 2, "g": 3, "a": 4, "b": 5, "c": 6 } ``` -------------------------------- ### Disallow Unnormalized JSON Keys (NFD Form) Source: https://github.com/eslint/json/blob/main/docs/rules/no-unnormalized-keys.md This example shows an incorrect JSON key when the rule is configured to use the NFD normalization form. A composed character like 'é' is invalid in NFD. ```jsonc /* eslint json/no-unnormalized-keys: ["error", { form: "NFD" }] */ { "café": "value", // é as a single code point is invalid in NFD } ``` -------------------------------- ### JSONSourceCode Constructor Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/json-source-code.md Initializes a new instance of the JSONSourceCode class. It takes configuration options including the source code text and the AST root node. ```APIDOC ## JSONSourceCode Constructor ### Description Initializes source code representation with text and AST. Automatically processes tokens and comments from the AST, builds indices for token lookups, and initializes traversal caching. ### Parameters #### Path Parameters - **options** (object) - Required - Configuration options - **options.text** (string) - Required - The complete source code text - **options.ast** (DocumentNode) - Required - The Momoa AST root node ### Example ```javascript import { JSONSourceCode } from "@eslint/json"; const sourceCode = new JSONSourceCode({ text: '{"name": "value"}', ast: documentNode }); ``` ``` -------------------------------- ### Configure sort-keys rule (with options) Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/rules.md Enables the 'sort-keys' rule with custom options for case sensitivity, natural sorting, minimum keys, and group separation. ```javascript "json/sort-keys": ["error", "asc", { caseSensitive: true, natural: false, minKeys: 2, allowLineSeparatedGroups: false }] ``` -------------------------------- ### Configure Rule Severity Levels Source: https://github.com/eslint/json/blob/main/_autodocs/configuration.md Shows the basic syntax for configuring ESLint rule severity levels, including 'off', 'warn', and 'error'. ```javascript rules: { "json/rule-name": "off" | "warn" | "error" } ``` -------------------------------- ### Initialize JSONSourceCode Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/json-source-code.md Instantiates the JSONSourceCode class with the source text and AST. This process automatically handles token and comment processing, builds lookup indices, and initializes traversal caching. ```javascript import { JSONSourceCode } from "@eslint/json"; const sourceCode = new JSONSourceCode({ text: '{"name": "value"}', ast: documentNode }); ``` -------------------------------- ### Main Plugin Export Source: https://github.com/eslint/json/blob/main/_autodocs/README.md Import the main ESLint plugin object for @eslint/json to configure languages, rules, and presets. ```APIDOC ## Main Plugin Export ### Description Import the main ESLint plugin object for @eslint/json to configure languages, rules, and presets. ### Usage ```javascript import json from "@eslint/json"; // Accessing plugin properties: // json.languages: { json, jsonc, json5 } // json.rules: { rule names mapped to definitions } // json.configs: { recommended } ``` ``` -------------------------------- ### Complete ESLint Configuration for JSON Variants Source: https://github.com/eslint/json/blob/main/_autodocs/configuration.md A comprehensive ESLint configuration object defining rules for .json, .jsonc, and .json5 files, including specific language options and rule settings. ```javascript import { defineConfig } from "eslint/config"; import json from "@eslint/json"; export default defineConfig([ { plugins: { json }, }, // Strict JSON files { files: ["**/*.json"], ignores: ["package-lock.json"], language: "json/json", rules: { "json/no-duplicate-keys": "error", "json/no-empty-keys": "error", "json/no-unnormalized-keys": "error", "json/no-unsafe-values": "error", "json/sort-keys": ["error", "asc", { caseSensitive: false, natural: true, }], }, }, // JSON with comments { files: ["**/*.jsonc", ".vscode/*.json", "tsconfig.json"], language: "json/jsonc", languageOptions: { allowTrailingCommas: true, }, rules: { "json/no-duplicate-keys": "error", "json/no-empty-keys": "error", "json/no-unnormalized-keys": "error", "json/no-unsafe-values": "error", }, }, // JSON5 files { files: ["**/*.json5"], language: "json/json5", rules: { "json/no-duplicate-keys": "error", "json/no-empty-keys": "error", "json/top-level-interop": "warn", }, }, ]); ``` -------------------------------- ### Instantiate JSONLanguage Source: https://github.com/eslint/json/blob/main/_autodocs/modules.md Create an instance of JSONLanguage to handle JSON, JSONC, and JSON5 parsing, AST generation, and token extraction. ```javascript import { JSONLanguage } from "@eslint/json"; const language = new JSONLanguage({ mode: "json" }); ``` -------------------------------- ### Inline ESLint Configuration for JSON Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/rules.md Illustrates how to use inline comments to enable or disable specific ESLint JSON rules within JSONC and JSON5 files. ```jsonc /* eslint json/no-empty-keys: "error" */ { "key": "value", "": "empty key" // error: empty key found } ``` ```jsonc /* eslint-disable json/no-duplicate-keys */ { "key": "value1", "key": "value2" // allowed } /* eslint-enable json/no-duplicate-keys */ ``` -------------------------------- ### Recommended ESLint JSON Rules Configuration Source: https://github.com/eslint/json/blob/main/_autodocs/modules.md Export a configuration object containing recommended rules for JSON linting, setting them to 'error' level. ```javascript const rules = { "json/no-duplicate-keys": "error", "json/no-empty-keys": "error", "json/no-unnormalized-keys": "error", "json/no-unsafe-values": "error", }; export default rules; ``` -------------------------------- ### Configure Specific JSON Rules Source: https://github.com/eslint/json/blob/main/_autodocs/index.md Configure specific rules like 'no-duplicate-keys' and 'sort-keys' with desired error levels and options. ```javascript rules: { "json/no-duplicate-keys": "error", "json/sort-keys": ["error", "asc", { caseSensitive: false, natural: true, }], } ``` -------------------------------- ### Create SourceCode Instance Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/json-language.md Generate a JSONSourceCode instance from a successful parse result. This instance provides access to source code text, tokens, comments, and AST information. ```javascript const parseResult = language.parse( { body: '{"name": "value"}' }, { languageOptions: {} } ); if (parseResult.ok) { const sourceCode = language.createSourceCode( { body: '{"name": "value"}' }, parseResult ); console.log("Comments:", sourceCode.comments); console.log("Lines:", sourceCode.lines); } ``` -------------------------------- ### traverse Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/json-source-code.md Initiates a traversal of the JSON source code's Abstract Syntax Tree, yielding steps for entering and exiting each node. ```APIDOC ## traverse ### Description Traverses the AST and returns traversal steps for entering and exiting each node. ### Returns An iterable of traversal steps, each containing: - `target`: The node being visited - `phase`: 1 for enter, 2 for exit - `args`: [node, parent] ### Behavior Steps are cached after the first call since the AST doesn't mutate. ### Example ```javascript for (const step of sourceCode.traverse()) { if (step.phase === 1) { console.log("Entering:", step.target.type); } else { console.log("Exiting:", step.target.type); } } ``` ``` -------------------------------- ### Node Visitor with Parent Access Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/custom-rules.md Illustrates how to define visitors for different node types (`Member`, `Element`, `String`) and access their parent nodes within the rule. ```javascript { Member(node, parent) { // node: MemberNode // parent: ObjectNode | undefined }, Element(node, parent) { // node: ElementNode // parent: ArrayNode | undefined }, String(node, parent) { // node: StringNode // parent: DocumentNode | MemberNode | ElementNode | undefined }, } ``` -------------------------------- ### Configure sort-keys Rule Options Source: https://github.com/eslint/json/blob/main/_autodocs/configuration.md Configures the `json/sort-keys` rule with options for sort direction, case sensitivity, natural sorting, minimum keys, and allowing line-separated groups. ```javascript "json/sort-keys": ["error", "asc" | "desc", { caseSensitive: boolean, natural: boolean, minKeys: number, allowLineSeparatedGroups: boolean }] ``` -------------------------------- ### Extract Raw Key with getRawKey Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/utilities.md Use `getRawKey` to extract the raw key text from source code, preserving original formatting and quoting. This is useful for user-facing messages. ```javascript import { getRawKey } from "@eslint/json"; // if exported // In a rule: const rule = { create(context) { return { Member(node) { const rawKey = getRawKey(node, context.sourceCode); console.log(`Raw Key: ${rawKey}`); }, }; }, }; // For: { "firstName": "John" } // Logs: Raw Key: "firstName" // For: { firstName: "John" } (JSON5) // Logs: Raw Key: firstName // For: { "first-name": "John" } // Logs: Raw Key: "first-name" ``` -------------------------------- ### Configure sort-keys rule (default) Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/rules.md Enables the 'sort-keys' rule with default ascending, case-sensitive order. ```javascript "json/sort-keys": "error" ``` -------------------------------- ### Exported Classes Source: https://github.com/eslint/json/blob/main/_autodocs/README.md Import the main classes for using the @eslint/json plugin in your ESLint configuration. ```APIDOC ## Exported Classes ### Description Import the main classes for using the @eslint/json plugin in your ESLint configuration. ### Usage ```javascript import { JSONLanguage, JSONSourceCode } from "@eslint/json"; ``` ``` -------------------------------- ### Import ESLint JSON Plugin Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/plugin.md Import the main plugin object from the @eslint/json package. This is the primary way to integrate JSON linting into your ESLint configuration. ```javascript import json from "@eslint/json"; ``` -------------------------------- ### Standard JSON Language Configuration Source: https://github.com/eslint/json/blob/main/_autodocs/configuration.md Configure ESLint to parse and lint standard JSON files. This configuration enforces no comments and disallows duplicate keys. ```javascript { files: ["**/*.json"], language: "json/json", rules: { "json/no-duplicate-keys": "error", }, } ``` -------------------------------- ### getInlineConfigNodes Source: https://github.com/eslint/json/blob/main/_autodocs/api-reference/json-source-code.md Retrieves all comment tokens within the JSON source code that match ESLint's inline configuration directive patterns. ```APIDOC ## getInlineConfigNodes ### Description Returns all inline configuration comments that match ESLint directive patterns. ### Returns Array of comment tokens that start with `eslint`, `eslint-enable`, `eslint-disable`, or `eslint-disable-next-line`. ### Example ```javascript const configNodes = sourceCode.getInlineConfigNodes(); // Returns comments like: // /* eslint json/no-duplicate-keys: "error" */ // // eslint-disable-next-line json/no-empty-keys ``` ``` -------------------------------- ### JSONLanguage Class Source: https://github.com/eslint/json/blob/main/_autodocs/MANIFEST.txt Documentation for the JSONLanguage class, including its constructor, properties, and methods. ```APIDOC ## Class: JSONLanguage ### Description Represents the JSON language parser and associated functionalities within the ESLint plugin. ### Constructor - `new JSONLanguage(options?: JSONLanguageOptions)`: Initializes a new instance of the JSONLanguage class. ### Properties - `properties`: Documentation for the properties of the JSONLanguage class. ### Methods - `method1()`: Description of the first method. - `method2()`: Description of the second method. - `method3()`: Description of the third method. ```