Giter Club home page Giter Club logo

eslint-plugin-jsonc's Introduction

Introduction

eslint-plugin-jsonc is ESLint plugin for JSON, JSONC and JSON5 files.

NPM license NPM version NPM downloads NPM downloads NPM downloads NPM downloads NPM downloads Build Status Coverage Status

📛 Features

This ESLint plugin provides linting rules relate to better ways to help you avoid problems when using JSON, JSONC and JSON5.

  • You can use ESLint to lint JSON.
  • You can apply rules similar to the rules you use for JavaScript to JSON using the "jsonc/auto" rule provided by this plugin.
  • You can choose the appropriate config provided by this plugin depending on whether you are using JSON, JSONC or JSON5.
  • Supports Vue SFC custom blocks such as <i18n>.
    Requirements vue-eslint-parser v7.3.0 and above.
  • Supports ESLint directives. e.g. // eslint-disable-next-line
  • You can check your code in real-time using the ESLint editor integrations.

You can check on the Online DEMO.

❓ Why is it ESLint plugin?

ESLint is a great linter for JavaScript.
Since JSON is a subset of JavaScript, the same parser and rules can be applied to JSON.
Also, JSONC and JSON5, which are variants of JSON, are more similar to JavaScript than JSON. Applying a JavaScript linter to JSON is more rational than creating a JSON-specific linter.

How does eslint-plugin-jsonc work?

This plugin parses .json with its own parser, but this parser just converts AST parsed by acorn (It is used internally by the ESLint standard parser) into AST with another name. However, ASTs that do not exist in JSON and the superset of JSON syntaxes are reported as parsing errors. By converting the AST to another name, we prevent false positives from ESLint core rules.
Moreover, You can do the same linting using the extended rules of the ESLint core rules provided by this plugin.

The parser package used by this plugin is jsonc-eslint-parser.

❓ How is it different from other JSON plugins?

Plugins that do not use AST

e.g. eslint-plugin-json

These plugins use the processor to parse and return the results independently, without providing the ESLint engine with AST and source code text.

Plugins don't provide AST, so you can't use directive comments (e.g. /* eslint-disable */).
Plugins don't provide source code text, so you can't use it with plugins and rules that use text (e.g. eslint-plugin-prettier, eol-last).
Also, most plugins don't support JSON5.

eslint-plugin-jsonc works by providing AST and source code text to ESLint.

Plugins that use the same AST as JavaScript

e.g. eslint-plugin-json-files, eslint-plugin-json-es

These plugins use the same AST as JavaScript for linting.

Since the plugin uses the same AST as JavaScript, it may not report syntax that is not available in JSON (e.g. 1 + 1, (42)). Also, ESLint core rules and other plugin rules can false positives (e.g. quote-props rule reports quote on keys), which can complicate the your configuration.

The AST used by eslint-plugin-jsonc is similar to JavaScript AST, but with a different node name. This will prevent false positives. This means that it can be easily used in combination with other plugins.

📖 Documentation

See documents.

💿 Installation

npm install --save-dev eslint eslint-plugin-jsonc

Requirements

  • ESLint v6.0.0 and above
  • Node.js v12.22.x, v14.17.x, v16.x and above

📖 Usage

Configuration

New Config (eslint.config.js)

Use eslint.config.js file to configure rules. See also: https://eslint.org/docs/latest/use/configure/configuration-files-new.

Example eslint.config.js:

import eslintPluginJsonc from 'eslint-plugin-jsonc';
export default [
  // add more generic rule sets here, such as:
  // js.configs.recommended,
  ...eslintPluginJsonc.configs['flat/recommended-with-jsonc'],
  {
    rules: {
      // override/add rules settings here, such as:
    // 'jsonc/rule-name': 'error'
    }
  }
];

This plugin provides configs:

  • *.configs['flat/base'] ... Configuration to enable correct JSON parsing.
  • *.configs['flat/recommended-with-json'] ... Recommended configuration for JSON.
  • *.configs['flat/recommended-with-jsonc'] ... Recommended configuration for JSONC.
  • *.configs['flat/recommended-with-json5'] ... Recommended configuration for JSON5.
  • *.configs['flat/prettier'] ... Turn off rules that may conflict with Prettier.
  • *.configs['flat/all'] ... Enables all rules. It's meant for testing, not for production use because it changes with every minor and major version of the plugin. Use it at your own risk.

This plugin will parse .json, .jsonc and .json5 by default using the configuration provided by the plugin (unless you already have a parser configured - see below).

See the rule list to get the rules that this plugin provides.

Legacy Config (.eslintrc)

Use .eslintrc.* file to configure rules. See also: https://eslint.org/docs/latest/use/configure/.

Example .eslintrc.js:

module.exports = {
  extends: [
    // add more generic rulesets here, such as:
    // 'eslint:recommended',
    "plugin:jsonc/recommended-with-jsonc",
  ],
  rules: {
    // override/add rules settings here, such as:
    // 'jsonc/rule-name': 'error'
  },
};

This plugin provides configs:

  • plugin:jsonc/base ... Configuration to enable correct JSON parsing.
  • plugin:jsonc/recommended-with-json ... Recommended configuration for JSON.
  • plugin:jsonc/recommended-with-jsonc ... Recommended configuration for JSONC.
  • plugin:jsonc/recommended-with-json5 ... Recommended configuration for JSON5.
  • plugin:jsonc/prettier ... Turn off rules that may conflict with Prettier.
  • plugin:jsonc/all ... Enables all rules. It's meant for testing, not for production use because it changes with every minor and major version of the plugin. Use it at your own risk.

This plugin will parse .json, .jsonc and .json5 by default using the configuration provided by the plugin (unless you already have a parser configured - see below).

See the rule list to get the rules that this plugin provides.

Parser Configuration

If you have already specified a parser in your .eslintrc, you will also need to manually configure the parser for JSON files (your parser config takes priority over that defined by extends shared configs).

For example, if you are using the "@babel/eslint-parser", configure it as follows:

module.exports = {
  // ...
  extends: ["plugin:jsonc/recommended-with-jsonc"],
  // ...
  parser: "@babel/eslint-parser",
  // Add an `overrides` section to add a parser configuration for json.
  overrides: [
    {
      files: ["*.json", "*.json5", "*.jsonc"],
      parser: "jsonc-eslint-parser",
    },
  ],
  // ...
};

💻 Editor Integrations

Visual Studio Code

Use the dbaeumer.vscode-eslint extension that Microsoft provides officially.

You have to configure the eslint.validate option of the extension to check .json files, because the extension targets only *.js or *.jsx files by default.

Example .vscode/settings.json:

{
  "eslint.validate": ["javascript", "javascriptreact", "json", "jsonc", "json5"]
}

✅ Rules

The --fix option on the command line automatically fixes problems reported by rules which have a wrench 🔧 below.
The rules with the following star ⭐ are included in the config.

JSONC Rules

Rule ID Description Fixable JSON JSONC JSON5
jsonc/auto apply jsonc rules similar to your configured ESLint core rules 🔧
jsonc/key-name-casing enforce naming convention to property key names
jsonc/no-bigint-literals disallow BigInt literals
jsonc/no-binary-expression disallow binary expression 🔧
jsonc/no-binary-numeric-literals disallow binary numeric literals 🔧
jsonc/no-comments disallow comments
jsonc/no-escape-sequence-in-identifier disallow escape sequences in identifiers. 🔧
jsonc/no-hexadecimal-numeric-literals disallow hexadecimal numeric literals 🔧
jsonc/no-infinity disallow Infinity
jsonc/no-nan disallow NaN
jsonc/no-number-props disallow number property keys 🔧
jsonc/no-numeric-separators disallow numeric separators 🔧
jsonc/no-octal-numeric-literals disallow octal numeric literals 🔧
jsonc/no-parenthesized disallow parentheses around the expression 🔧
jsonc/no-plus-sign disallow plus sign 🔧
jsonc/no-regexp-literals disallow RegExp literals
jsonc/no-template-literals disallow template literals 🔧
jsonc/no-undefined-value disallow undefined
jsonc/no-unicode-codepoint-escapes disallow Unicode code point escape sequences. 🔧
jsonc/sort-array-values require array values to be sorted 🔧
jsonc/sort-keys require object keys to be sorted 🔧
jsonc/valid-json-number disallow invalid number for JSON 🔧
jsonc/vue-custom-block/no-parsing-error disallow parsing errors in Vue custom blocks

Extension Rules

Rule ID Description Fixable JSON JSONC JSON5
jsonc/array-bracket-newline enforce line breaks after opening and before closing array brackets 🔧
jsonc/array-bracket-spacing disallow or enforce spaces inside of brackets 🔧
jsonc/array-element-newline enforce line breaks between array elements 🔧
jsonc/comma-dangle require or disallow trailing commas 🔧
jsonc/comma-style enforce consistent comma style 🔧
jsonc/indent enforce consistent indentation 🔧
jsonc/key-spacing enforce consistent spacing between keys and values in object literal properties 🔧
jsonc/no-dupe-keys disallow duplicate keys in object literals
jsonc/no-floating-decimal disallow leading or trailing decimal points in numeric literals 🔧
jsonc/no-irregular-whitespace disallow irregular whitespace
jsonc/no-multi-str disallow multiline strings
jsonc/no-octal-escape disallow octal escape sequences in string literals
jsonc/no-octal disallow legacy octal literals
jsonc/no-sparse-arrays disallow sparse arrays
jsonc/no-useless-escape disallow unnecessary escape usage
jsonc/object-curly-newline enforce consistent line breaks inside braces 🔧
jsonc/object-curly-spacing enforce consistent spacing inside braces 🔧
jsonc/object-property-newline enforce placing object properties on separate lines 🔧
jsonc/quote-props require quotes around object literal property names 🔧
jsonc/quotes enforce use of double or single quotes 🔧
jsonc/space-unary-ops disallow spaces after unary operators 🔧

🚀 To Do More Verification

Verify using JSON Schema

You can verify using JSON Schema by checking and installing eslint-plugin-json-schema-validator.

Verify the Vue I18n message resource files

You can verify the message files by checking and installing @intlify/eslint-plugin-vue-i18n.

🚥 Semantic Versioning Policy

eslint-plugin-jsonc follows Semantic Versioning and ESLint's Semantic Versioning Policy.

🍻 Contributing

Welcome contributing!

Please use GitHub's Issues/PRs.

Development Tools

  • npm test runs tests and measures coverage.
  • npm run update runs in order to update readme and recommended configuration.

👫 Related Packages

🔒 License

See the LICENSE file for license rights and limitations (MIT).

eslint-plugin-jsonc's People

Contributors

bitfactory-oussama-fadlaoui avatar chris-reeves avatar cjoecker avatar clemyan avatar danielrentz avatar duncanbeevers avatar github-actions[bot] avatar joshuakgoldberg avatar kecrily avatar logicer16 avatar ota-meshi avatar renovate-bot avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

eslint-plugin-jsonc's Issues

sort-keys: Misplaced comments in tsconfig.json

description

  • sort-keys misplaces the comments in a tsconfig.json

reproduction

  • create a package.json
{
  "dependencies": {
    "eslint": "^8.49.0",
    "eslint-plugin-jsonc": "^2.9.0"
  },
  "eslintConfig": {
    "plugins": [
      "eslint-plugin-jsonc"
    ],
    "parser": "jsonc-eslint-parser",
    "rules": {
      "jsonc/sort-keys": [
        "error",
        {
          "pathPattern": "^compilerOptions$",
          "order": [
            "target",
            "strict"
          ]
        }
      ]
    }
  }
}
  • create a tsconfig.json
{
  "compilerOptions": {
    "strict": true, /* Enable all strict type-checking options. */
    "target": "esnext" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
  }
}
  • after applying the rule the tsconfig.json transforms into:
{
  "compilerOptions": { /* Enable all strict type-checking options. */
    "target": "esnext",
    "strict": true /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
  }
}

reference

Question: vscode and JSON5 syntax highlight

This plugin is so good that I'd like to just rely on it when using VSCode instead of using the unmaintained JSON5 extension.
To do so I associate .json5 files to JavaScript.

  "files.associations": {
    "*.json5": "javascript"
  },
  "[json5]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "dbaeumer.vscode-eslint"
  },

The problem that I still have is that JS validation is on because of this setting:

"javascript.validate.enable": true,

My wish is to disable this for JSON5, but not for JS files. Has anyone been in this situation before?

Adding no-duplicate-values-in-json files rule feature to the plugin

Hi there,
I have been searching for a no duplicate values in a json file (not keys, but values) rule or plugin. I believe it can be beneficial. I have written the logic myself already but have problems when it integrates to eslint. I could collaborate and add that feature to this plugin. That way can be beneficial for other people looking for this feature.
Best,
Thanks.

Enable the appropriate recommended config according to the extension

I read the code but didn't get it.

If I use the recommended configuration for .json, .jsonc and .json5 at the same time, will it automatically use the appropriate configuration based on the file extension?

If not, what do I have to do to get them to use the appropriate configuration based on the extension.

Request textDocument/codeAction failed.

I provided a Testrepo where it is pretty easy to reproduce this error within the Output of Eslint within Visual Studio Code.

  1. npm i
  2. Open foo.json
  3. Go to the Eslint Output within Visual Studio Code

That's it.

[Info  - 1:13:01 AM] ESLint server is starting.
[Info  - 1:13:02 AM] ESLint server running in node v16.17.1
[Info  - 1:13:02 AM] ESLint server is running.
[Info  - 1:13:04 AM] ESLint library loaded from: C:\Home\tmp\eslint\node_modules\eslint\lib\api.js
[Error - 1:13:12 AM] Request textDocument/codeAction failed.
  Message: Request textDocument/codeAction failed with message: Invalid regular expression: //** eslint-disable-next-line/: Nothing to repeat
  Code: -32603 

What is the reason for this error?

I cannot find any regular expression that looks like the one within the error message, not even within node_modules.

When running with fix flag, not all files are automatically fixed

I have a project with lets say 30 JSON files that need to be sorted case sensitive.

I run the command eslint ./**/*.json --fix

Then I run it again without the fix flag and learn that it has only fixed 13 out of 30 files:

✖ 17 problems (17 errors, 0 warnings)
  17 errors and 0 warnings potentially fixable with the `--fix` option.

I repeat the process above and get down to 13 errors, then 10 errors, etc.

Any idea why eslint --fix does not fix all my files in one go?

I'm running this inside a Next.js project using the built-in linting settings. In addition I have the following configuration in .eslintrc.js:

...
    'jsonc/sort-keys': [
      'error',
      'asc',
      {
        caseSensitive: true,
        natural: false,
        minKeys: 2,
      },
    ],
...

Any idea what might be going on?

Sorting Arrays Alphabetically

Hey, is it possible to have this plugin sort arrays alphabetically? For instance, the keywords in package.json -- I can't figure out how to get this plugin to sort them.

support validate some keys is grouped

all key starts with build should be grouped.

bad:

"scripts": {
    "preinstall": "",
    "build:design": "",
    "clean": "",
    "build:analyze": "",
    "build": "",
    "preview:design": "",
}

good:

"scripts": {
    "preinstall": "",
    "clean": "",
    "build:design": "",
    "build:analyze": "",
    "build": "",
    "preview:design": "",
}

Error: Cannot find module 'espree'

When changing from ~2.10.0 (resolved as 2.10.0) to ~2.11.0 (resolved as 2.11.1)
image

I am getting the following error when running using pnpm:

Error: Cannot find module 'espree'
Require stack:
- /home/runner/node_modules/.store/eslint-plugin-jsonc-virtual-f2fb243113/node_modules/eslint-plugin-jsonc/dist/utils/eslint-ast-utils.js
- /home/runner/node_modules/.store/eslint-plugin-jsonc-virtual-f2fb243113/node_modules/eslint-plugin-jsonc/dist/rules/array-bracket-newline.js
- /home/runner/node_modules/.store/eslint-plugin-jsonc-virtual-f2fb243113/node_modules/eslint-plugin-jsonc/dist/utils/rules.js
- /home/runner/node_modules/.store/eslint-plugin-jsonc-virtual-f2fb243113/node_modules/eslint-plugin-jsonc/dist/index.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1144:15)
    at Module._load (node:internal/modules/cjs/loader:985:27)
    at Module.require (node:internal/modules/cjs/loader:1235:19)
    at require (node:internal/modules/helpers:176:18)
    at Object.<anonymous> (/home/runner/node_modules/.store/eslint-plugin-jsonc-virtual-f2fb243113/node_modules/eslint-plugin-jsonc/dist/utils/eslint-ast-utils.js:5:18)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Module._load (node:internal/modules/cjs/loader:1023:12)
    at Module.require (node:internal/modules/cjs/loader:1235:19)

I think we need to add espree into the dependencies, or into the peerDependencies.

Add only allow flattened/nested keys rule

Would it be possible to add a rule to only allow flattened JSON files (and rule to allow only nested key properties would then also probably be needed). It would work by checking if the value is an object or if it is just a number or a string. For the rule to only allow nested keys you could just simply check if the keys contain dots or not.

This would be a useful rule to ensure code contributors follow the same rules when adding keys to translation files.

Example of how this rule would work:

/* eslint jsonc/nested-keys: ["error", "never"] */
{
    /* ✓ GOOD */
    "GOOD": {
        "home.news.title": "Home News"
    }

    /* ✗ BAD */
    "BAD": {
        "home": {
            "news.title": "Home News"
         }
     }
}
/* eslint jsonc/nested-keys: ["error", "always"] */
{
    /* ✓ GOOD */
    "GOOD": {
        "home": {
            "news": {
                "title": "Home News"
            }
        }
    }

    /* ✗ BAD */
    "BAD": {
        "home.news.title": "Home News"
    }
}

Error importing this plugin in Vite application

Hi and many thanks for creating this plugin, it's very useful to me!

I am trying to run this plugin in the browser using Vite and eslint4b, but I am getting an error when I import it:

[ERROR] Could not read from file: /Users/grebonato/Code/mino-lint/virtual:eslint4b_eslint

node_modules/eslint-plugin-jsonc/dist/utils/index.js:117:37:
  117 │         ruleMap = map = new (require("eslint").Linter)().getRules();

Here is the repository with the error.
It's a Vite project and I am using vite-plugin-eslint4b to load eslint.

Do you know what's going on?
I tried to figure out by looking at how you created the playground, but I am missing something.

Version 3

  • Drop support for older versions of Node.js. (<18?)
  • Drop support for older versions of ESLint. (<8?)
  • Support for flat shareable configs. (Do we want to release it before the new version?)
  • And more?

When using it with `@typescript-eslint/consistent-type-exports`

I get an error when integrating this plugin while also using @typescript-eslint/consistent-type-exports.

Here's an extract out of my .eslintrc:

  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "project": "tsconfig.json",
    "sourceType": "module"
  },
  "overrides": [
    {
      "files": ["*.json", "*.jsonc", "*.json5"],
      "parser": "jsonc-eslint-parser"
    }
  ],
  "plugins": [
    "import"
  ],
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended",
    "plugin:jsonc/recommended-with-json",
    "prettier"
  ],

Upon using this, I end up with:

Oops! Something went wrong! :(

ESLint: 8.17.0

Error: Error while loading rule '@typescript-eslint/consistent-type-exports': You have used a rule which requires parserServices to be generated. You must therefore provide a value for the "parserOptions.project" property for @typescript-eslint/parser.
Occurred while linting /home/cmcdragonkai/Projects/Polykey/src/tokens/schemas/TokenHeaderSignatureSchema.json
    at Object.getParserServices (/home/cmcdragonkai/Projects/Polykey/node_modules/@typescript-eslint/utils/dist/eslint-utils/getParserServices.js:15:15)
    at create (/home/cmcdragonkai/Projects/Polykey/node_modules/@typescript-eslint/eslint-plugin/dist/rules/consistent-type-exports.js:64:37)
    at Object.create (/home/cmcdragonkai/Projects/Polykey/node_modules/@typescript-eslint/utils/dist/eslint-utils/RuleCreator.js:41:20)
    at createRuleListeners (/home/cmcdragonkai/Projects/Polykey/node_modules/eslint/lib/linter/linter.js:922:21)
    at /home/cmcdragonkai/Projects/Polykey/node_modules/eslint/lib/linter/linter.js:1104:31
    at Array.forEach (<anonymous>)
    at runRules (/home/cmcdragonkai/Projects/Polykey/node_modules/eslint/lib/linter/linter.js:1041:34)
    at Linter._verifyWithoutProcessors (/home/cmcdragonkai/Projects/Polykey/node_modules/eslint/lib/linter/linter.js:1389:31)
    at Linter._verifyWithConfigArray (/home/cmcdragonkai/Projects/Polykey/node_modules/eslint/lib/linter/linter.js:1729:21)
    at Linter.verify (/home/cmcdragonkai/Projects/Polykey/node_modules/eslint/lib/linter/linter.js:1471:65)

If I remove this plugin, things work again.

It seems the addition of the overrides ends up causing that above problem.

Conflict with @typescript-eslint/recommended-requiring-type-checking?

Use this plugin with extends '@typescript-eslint/recommended-requiring-type-checking' rules take ESLint error:

Error: You have used a rule which requires parserServices to be generated. You must therefore provide a value for the "parserOptions.project" property for @typescript-eslint/parser.

.eslintrc.js:

module.exports = {
  root: true,
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:@typescript-eslint/recommended-requiring-type-checking', // Comment this line fix the error
    'plugin:jsonc/recommended-with-jsonc',
    'plugin:astro/recommended',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 'latest',
    project: true,
    tsconfigRootDir: __dirname,
  },
  overrides: [
    {
      files: ['*.json', '*.json5', '*.jsonc'],
      parser: 'jsonc-eslint-parser',
      // Add this lines make ESLint Error: You have used a rule which requires parserServices to be generated. You must therefore provide a value for the "parserOptions.project" property for @typescript-eslint/parser.
    },
    {
      files: ['*.astro'],
      parser: 'astro-eslint-parser',
      parserOptions: {
        parser: '@typescript-eslint/parser',
        extraFileExtensions: ['.astro'],
      },
    },
  ],
};

Reproduction repo: https://stackblitz.com/edit/github-pjptru?file=.eslintrc.cjs&view=editor

Question: How to format on save in VSCode?

I've got this plugin properly linting and I've got the following in my .vscode/settings.json:

{
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
  },
  "eslint.validate": ["javascript", "javascriptreact", "json", "jsonc", "json5"]
}

Is there some other setting or option I'm missing to apply fix on save for files that this plugin lints?

Cannot parse or format JSON files in VScode, or CLI

So I've done the following:

1. Install the package:

npm i -D eslint-plugin-jsonc`

2. Added only to the extends section in my .eslintrc.json, like so:

  "extends": [
    "eslint:recommended",
    "plugin:jsonc/recommended-with-jsonc",
    "next"
  ],

I did not configure anything else there. Just this!
And yes, it's a Next.js project. Shouldn't matter, but there you go.

3. Added the following configuration to my workspace settings: (in ./.vscode/settings.json)

  "eslint.enable": true,
  "eslint.useESLintClass": true,
  "eslint.alwaysShowStatus": true,
  "editor.codeActionsOnSave": {
    "source.fixAll": false,
    "source.fixAll.eslint": true
  },
  "[json]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "dbaeumer.vscode-eslint"
  },
  "[jsonc]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "dbaeumer.vscode-eslint"
  },
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact",
    "json",
    "jsonc"
  ],

And restarted VSCode.
(It doesn't actually matter where (workspace/user settings) or if at all this is added, as you'll see further on. It'll break on the commandline before anything else, so I might as well leave this whole step out, frankly. I'm going to leave it in for completeness though.)

4. Time to test it out!

So I've added a dead simple file, called test.json:

{
  "foo": "bar"
}

Results

On the commandline

First I installed eslint globally:

npm i -g eslint

When executing eslint test.json I get the following error:

D:\[redacted]\test.json
  2:7  error  Parsing error: D:\[redacted]\test.json: Missing semicolon. (2:7)

  1 | {
> 2 |   "foo": "bar"
    |        ^
  3 | }
  4 |

✖ 1 problem (1 error, 0 warnings)

Semicolons in JSON 🤨 It doesn't feel quite right to me...

In VSCode

Opening that marvellously simple test file again, I get the same error on the problems panel.

When pressing Ctrl+S, I get a message on the status bar that says:

Extension 'ESLint' is configured as formatter but it cannot format `JSON`-files

This makes sense given that ESLint cannot even seem to parse a super simple json file... If it can't parse them properly, how could it ever format them, right?

What's going on? It's probably some stupid setting or a tiny little thing I've missed, because I can't believe this package being utterly broken. It doesn't feel like that kind of package 😊 It feels professional 😎 So maybe something is borking things up 🤔

Internal code suggestion: add explicit call signatures for RuleListener node types?

Found when looking into ota-meshi/jsonc-eslint-parser#184: this package's rules seem to completely ignore estree types, and instead replace node types with their own AST.JSON* types.

export interface RuleListener {
[key: string]: ((node: never) => void) | undefined;
}

JSONLiteral(node: AST.JSONLiteral) {

Would you be open to a PR that adds a few explicit call signatures that have a type for the RuleListener's node? We use this strategy in typescript-eslint to remove the need for most node: ... type annotations in our rules.

export interface RuleListener {
  JSONBinaryExpression: ((node: AST.JSONBinaryExpression) => void) | undefined;
  JSONLiteral: ((node: AST.JSONLiteral) => void) | undefined;
  // ...
  [key: string]: ((node: never) => void) | undefined;
}

In theory this could be automated with TypeScript type magicks. I haven't looked into it.

Allow ignoring certain paths from sorting

👋 I'm a big fan of this plugin and use it in http://github.com/JoshuaKGoldberg/template-typescript-node-package to sort package.json contents. Thanks for making it!

Turns out sometimes package.json content ordering does matter. Per https://www.typescriptlang.org/docs/handbook/esm-node.html#packagejson-exports-imports-and-self-referencing, the types resolution under "exports" > "." must come first:

// package.json
{
    "exports": {
        ".": {
            // Entry-point for TypeScript resolution - must occur first!
            "types": "./types/index.d.ts",
            // Entry-point for `import "my-package"` in ESM
            "import": "./esm/index.js",
            // Entry-point for `require("my-package") in CJS
            "require": "./commonjs/index.cjs",
        },
    }
}

Would you be open to a config option allowing to exclude certain object property paths? Maybe:

module.exports = {
	overrides: [
		{
			files: "*.json",
			parser: "jsonc-eslint-parser",
			rules: {
				"jsonc/sort-keys": [
					"error",
					{
						ignore: ["exports", "."],
					},
				],
			},
		},
	],
};

...I'm not confident in that ignore: string[] format. But can't think of a better option right now. 🤔

Potentially relevant: typescript-eslint/typescript-eslint#6017

Ignore key for sort-keys and no-dupe-keys

Is there a way to "ignore a key" for sort-keys and no-dupe-keys?

The case I want to get working is commenting the scripts in package.json by using "//" keys as suggested in the following link:
https://stackoverflow.com/a/14221781

The problem is that using "//" will conflict with sort-keys and no-dupe-keys rules, and I want to continue enforcing those rules but with all of "//" keys under scripts ignored.

I think it might be nice to introduce an option to ignore a key if there isn't one already.

Example rule:

{
    "jsonc/no-dupe-keys": ["error",
        {
            "ignoreKeys": ["//"]
        }
    ],
    "jsonc/sort-keys": ["error",
        {
            "ignoreKeys": ["//"]
        }
    ]
}

Example correct input:

{
  "scripts": {
    "//": "build project",
    "build": "...",
    "//": "serve project for development",
    "dev": "...",
    "//": "serve project for production",
    "start": "..."
  }
}

Example incorrect input:

// sort-keys
{
  "scripts": {
    "//": "serve project for development",
    "dev": "...",
    "//": "build project",
    "build": "...",
    "//": "serve project for production",
    "start": "..."
  }
}

// no-dupe-keys
{
  "scripts": {
    "//": "serve project for development",
    "build": "...",
    "//": "build project",
    "build": "...",
    "//": "serve project for production",
    "start": "..."
  }
}

Explicit error message of jsonc/sort-keys

Hello 👋

When using the rule jsonc/sort-keys with more than 2 properties the error message is not clear where the correct placement of the property should be, for instance, imagine the following scenario:

.eslintrc

"jsonc/sort-keys": [
  "error",
  {
    "pathPattern": "^$",
    "order": [
      "prop-one",
      "prop-two",
      "prop-three",
      "prop-four"
    ]
  }
]

some.json

{
  "prop-two": { /* data */ },
  "prop-three": { /* data */ },
  "prop-four": { /* data */ },
  "prop-one": { /* data */ }
}

With the file above, this would yield the following error message:

L:C  error  Expected object keys to be in specified order. 'prop-one' should be before 'prop-four'  jsonc/sort-keys

Which is not incorrect, but it would be much better, to either provide the user the order that should be followed or instead:

(...) 'prop-one' should be before 'prop-two'  jsonc/sort-keys

Otherwise the user will just assume that has to move the property prop-one before the prop-four and the error will be fixed, which is not the case.

Thanks for your time 🙏

Dependency Dashboard

This issue provides visibility into Renovate updates and their statuses. Learn more

This repository currently has no open or pending branches.


  • Check this box to trigger a request for Renovate to run again on this repository

feat: sort-keys to take properties array

I'd like to pass in an array of properties to enforce an order. Similar to your vue/order-in-components rule.

For context, I'm planning to use this rule to lint package.json files, so sorting the keys alphabetically doesn't make too much sense.

Since sort-keys is based off of the official sort-keys rule, I think creating another rule (eg. keys-order/properties-order) would make sense too.

Thank you for all these amazing ESLint plugins BTW!

vscode-eslint extension cannot validate JSON using the "eslint.probe" configuration

The following content is from the setting options of vscode-eslint

  • eslint.probe - an array for language identifiers for which the ESLint extension should be activated and should try to validate the file. If validation fails for probed languages the extension says silent. Defaults to ["javascript", "javascriptreact", "typescript", "typescriptreact", "html", "vue", "markdown"].
  • eslint.validate - an array of language identifiers specifying the files for which validation is to be enforced. This is an old legacy setting and should in normal cases not be necessary anymore. Defaults to ["javascript", "javascriptreact"].

I can only use "eslint.validate": ["json"] in my settings.json for the validation to take effect.

Add .jsonc into overrides.files

Could you add .jsonc into:

// https://github.com/ota-meshi/eslint-plugin-jsonc/blob/master/lib/configs/base.ts

export = {
    plugins: ["jsonc"],
    overrides: [
        {
            files: ["*.json", "*.jsonc", "*.json5"],
            parser: require.resolve("jsonc-eslint-parser"),
            rules: {
                // ESLint core rules known to cause problems with JSON.
                strict: "off",
                "no-unused-expressions": "off",
            },
        },
    ],
}

I would appreciate it because I use .jsonc extension too. Thanks.

Failed linting of JSON fragments in Markdown on GitLab CI

When linting JSON fragments in Markdown file using eslint-plugin-markdown linting throw an error. But this can be reproduced only in GitLab CI environment but not local. I believe it depends on OS. GitLab is Linux, local is Windows.
Also tried on a similar but another project using Travis and it didn't fail.

Pay attention to the "virtual" file path /builds/company_name/repository_name/README.md/2_2.json. The exception itself is thrown by ESLint function when thi s expression is called directoryExists('C:\Projects\Projects_Compane\project_name\README.md\2_2.json') when linter meets the first JSON code

Oops! Something went wrong! :(
ESLint: 7.16.0
Error: ENOTDIR: not a directory, stat '/builds/company_name/repository_name/README.md/2_2.json'
    at Object.statSync (fs.js:1016:3)
    at directoryExists (/builds/company_name/repository_name/node_modules/eslint/lib/cli-engine/cli-engine.js:532:19)
    at CLIEngine.getConfigForFile (/builds/company_name/repository_name/node_modules/eslint/lib/cli-engine/cli-engine.js:944:13)
    at getConfig (/builds/company_name/repository_name/node_modules/eslint-plugin-jsonc/dist/processors/auto-config.js:13:27)
    at preprocess (/builds/company_name/repository_name/node_modules/eslint-plugin-jsonc/dist/processors/auto-config.js:22:24)
    at Linter._verifyWithProcessor (/builds/company_name/repository_name/node_modules/eslint/lib/linter/linter.js:1292:30)
    at Linter._verifyWithConfigArray (/builds/company_name/repository_name/node_modules/eslint/lib/linter/linter.js:1264:25)
    at /builds/company_name/repository_name/node_modules/eslint/lib/linter/linter.js:1312:29
    at Array.map (<anonymous>)
    at Linter._verifyWithProcessor (/builds/company_name/repository_name/node_modules/eslint/lib/linter/linter.js:1292:65)
npm ERR! code ELIFECYCLE
npm ERR! errno 2

What difference I noticed that local Windows environment throws ENOENT error which is chedked in condition in directoryExists() function and returned as false. But GitLab env throws ENOTDIR which is escalated and thrown on eslint-plugin-jsonc/dist/processors/auto-config.js:13:27

How config correctly my eslint config with jsonc

My eslint config :

module.exports = {
  rules: {
    "object-curly-newline": [
      "error",
      {
        ExportDeclaration: "always",
        ObjectExpression: "always",
        ImportDeclaration: "never",
        ObjectPattern: "always"
      }
    ],
    "@stylistic/array-bracket-newline": [
      "error",
      "always"
    ],
    "@stylistic/array-element-newline": [
      "error",
      "always"
    ],
    "@typescript-eslint/comma-dangle": [
      "error",
      "never"
    ],
    "@typescript-eslint/quotes": [
      "error",
      "double"
    ],
    "@typescript-eslint/semi": [
      "error",
      "never"
    ],
    "@stylistic/object-property-newline": "error"
  },
  extends: [
    "next/core-web-vitals",
    "airbnb",
    "airbnb/hooks",
    "airbnb-typescript",
    "plugin:perfectionist/recommended-line-length",
    "plugin:tailwindcss/recommended",
    "plugin:jsonc/recommended-with-json"
  ],
  overrides: [
    {
      files: [
        "*.json"
      ],
      parser: "jsonc-eslint-parser"
    }
  ],
  parserOptions: {
    project: "tsconfig.json"
  },
  globals: {
    React: "writable"
  },
  plugins: [
    "@stylistic"
  ]
}

Error i get :

npx eslint . --fix

Oops! Something went wrong! :(

ESLint: 8.56.0

Error: Error while loading rule '@typescript-eslint/naming-convention': You have used a rule which requires parserServices to be generated. You must therefore provide a value for the "parserOptions.project" property for @typescript-eslint/parser.
Note: detected a parser other than @typescript-eslint/parser. Make sure the parser is configured to forward "parserOptions.project" to @typescript-eslint/parser

Sorting by Order in Multiple Ways

Hey, I'm trying to get this plugin to put the name in package.json first, then version second, and then after that everything alphabetically... is it possible to use two sort methods at the same time like this?

Add brace-style rule

It would be awesome to have a brace-style rule for json files as I usually work with Allman style and would love to enforce this. Thanks for the plugin, keep on the good work.

Unexpected Strings must use singlequote error - Conflicting with another rule

module.exports = {
  env: {
    browser: true,
    es6: true,
    node: true,
    jest: true,
  },
  parser: '@typescript-eslint/parser', // Specifies the ESLint parser
  extends: [
    'plugin:react/recommended', // uses react-specific linting rules
    'plugin:@typescript-eslint/recommended', // uses typescript-specific linting rules
    'plugin:import/errors',
    'plugin:import/warnings',
    'plugin:import/typescript',
    'plugin:prettier/recommended', // enables eslint-plugin-prettier and eslint-config-prettier
    'prettier/react', // disables react-specific linting rules that conflict with prettier
    'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
    'plugin:jsonc/recommended-with-json', // JSON formatting
    'plugin:jsonc/prettier', // JSON formatting
  ],
  rules: {
    quotes: ['error', 'single', 'avoid-escape'], // single for .js
    'jsonc/quotes': ['error', 'double', { avoidEscape: false }], // double for .json
  },
}
yarn eslint src/app/locales/en-US.json

...
  2314:7   error  Strings must use singlequote  [quotes]
  2314:9  error  Strings must use singlequote  [quotes]
  2314:20   error  Strings must use singlequote  [quotes]
...
etc

eslint 7.32.0
eslint-plugin-jsonc 2.3.1

Any ideas? :)

"jsonc/no-comments" rule - [bug] some comments are ignored

It is possible to simulate the error with the code:

{
  /* hi */
  // test
  "name": "John"
}

or

{
  // test
  "name": "John"
}

or

{
  "name": "John",
  "test": "test",
  // test
  "test2": "test"
}

plugin-jsonc

WebStorm has its own JSON validator, which means that WebStorm identifies the error because there should not be comments in a JSON file. However, the warning from eslint-plugin-jsonc does not appear. If you look at the terminal in the image, you will see the command to run eslint on the same file, and nothing happens because the error is not detected. Initially, I thought it was an error only with comments made at the beginning of the block, but that's not the case. I have managed to enforce the rule "jsonc/no-comments," but generally, it doesn't work.

Keep getting "Parsing error: Expected to be an expression, but got empty"

I just tried a very small simple case, and I keep receiving this error.

Config eslint-config.js

module.exports = {
  extends: ['plugin:jsonc/recommended-with-jsonc'],
  // rules: {},
};

The target eslint-to-test.json

{
  "b": "bbb",
  "a": "aaa"
}

cli:

npx eslint -c eslint-config.js eslint-to-test.json

/.../eslint-to-test.json
  1:2  error  Parsing error: Expected to be an expression, but got empty

✖ 1 problem (1 error, 0 warnings)

What am I missing?!

Compatibility issue with eslint-plugin-vuejs-accessibility

When I try to use https://github.com/vue-a11y/eslint-plugin-vuejs-accessibility in the config together with eslint-plugin-jsonc something doesn't work as expected. eslint-plugin-vuejs-accessibility utilizes vue-eslint-parser (its peer dependency). Thats why when JSON files are linted it fails with an exception

Oops! Something went wrong! :(

ESLint: 7.18.0

TypeError: Error while loading rule 'vuejs-accessibility/interactive-supports-focus': context.parserServices.defineTemplateBodyVisitor is not a function

The ESLint config is like this (simplified example):

{
  "plugins": [
    "jsonc",
    "vue",
    "vuejs-accessibility"
  ],
  "parser": "vue-eslint-parser",
  "overrides": [
    {
      "files": ["*.json", "*.jsonc", "*.json5", "*.json6"],
      "parser":"jsonc-eslint-parser",
      "rules": {
        "jsonc/auto": "error"
      }
    }
  ],
  "rules": {
     "jsonc/indent": "error",
     "vuejs-accessibility/accessible-emoji": "error",
     // many rules
  }
}

And of course ESLint fails as we have overridden the parser for JSON files

I tried also another approach as Vue Plugin suggest - use "parserOptions.parser"

{
  "plugins": [
    "jsonc",
    "vue",
    "vuejs-accessibility"
  ],
  "parser": "vue-eslint-parser",
  "overrides": [
    {
      "files": ["*.json", "*.jsonc", "*.json5", "*.json6"],
      "parserOprions": {
        "parser":"jsonc-eslint-parser",
      },
      "rules": {
        "jsonc/auto": "error"
      }
    }
  ],
  "rules": {
     "jsonc/indent": "error",
     "vuejs-accessibility/accessible-emoji": "error",
     // many rules
  }
}

Now plugins work. Many core rules are also linted. But jsonc rules are not checked any more. For example "jsonc/indent" errors are not reported.

Expected

One of both

  1. vuejs-accessibility/* rules should not throw when the parser is not vue-eslint-parser and just ignore
  2. All jsonc/* rules are applied when configured with { "parser": "vue-eslint-parser", "parserOprions": { "parser":"jsonc-eslint-parser" } }

Support configuration file eslint.config.js

ESLint is introducing a new flat configuration file structure. They make the statement We are transitioning to a new config system in ESLint v9.0.0. The config system shared on this page is currently the default but will be deprecated in v9.0.0. at https://eslint.org/docs/latest/use/configure/configuration-files. The new structure is described at https://eslint.org/docs/latest/use/configure/configuration-files-new.

I believe some changes are required for eslint-plugin-jsonc to work with the new format.

sort-keys need to run many times to sort big files

Steps to reproduce

  1. Add an unsorted JSON file with more than 200 entries
  2. Add "jsonc/sort-keys": ["error"] to the eslint config
  3. Run eslint fix

Current behavior

Eslint show errors for some entries that couldn't be sorted.
After running eslint fix many times, the file is finally sorted.

Expected behavior

eslint fix needs to run only ones and all keys are then sorted without any further errors

Unexpected `Strings must use singlequote` error on `jsonc/auto` rule?

```json
{
  "plugins": [
    "preset-lint-consistent",
    "preset-lint-recommended",
    "preset-lint-markdown-style-guide",
    "preset-prettier"
  ]
}
```

JSON in markdown, parsed by eslint-mdx with mdx/code-blocks setting enabled.

My related eslint config: https://github.com/1stG/configs/blob/master/packages/eslint-config/overrides.js#L490-L513 and prettier-config: https://github.com/1stG/configs/blob/master/packages/prettier-config/base.js

It is processed as x.md/0_x.json as virtual filename.

Documentation: more detailed explanation or an example for auto-config

plugin:jsonc/auto-config ... Automatically apply jsonc rules similar to your configured ESLint core rules to JSON.

I find it difficult to understand what stand behind this description. And it's not easy to figure out from the code.

Some example might be helpful.

Update:

I now see that it is about the rules borrowed from ESlint. But this raises another question:
How do I combine JSONC own rules recommended for *.jsonc with auto-configured borrowed rules?
Will this work?:

{
  "extends": [
    ...,
    "plugin:jsonc/auto-config",
    "plugin:jsonc/recommended-with-jsonc",
    ...
  ]
}

It does seem to work. Although I'm not sure whether it is a good way to use it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.