Giter Site home page Giter Site logo

eslint-plugin-json's People

Contributors

adrieankhisbe avatar arcanemagus avatar azeemba avatar bebraw avatar bepo65 avatar edg2s avatar erikengervall avatar michaeldeboey avatar michaelmior avatar standard8 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  avatar

eslint-plugin-json's Issues

Version problems with npm

In master branch version is currently 3.0.0. In releases there is v3.0.0 tag. However, in npm the latest version is 3.1.0. There is no v3.1.0 tag in here. What's wrong?

Finding duplicate values instead of keys

Is it at all feasible to create a rule that checks for duplicate (or similar) values rather than keys? I'm not all too familiar with eslint plugin development, but I recently learned about the Levenshtein Distance and I thought it'd be a great addition to lint our i18n language files with.

`json/*` rules should be avoided where possible

For example in the definition of the recommended ruleset, which most users will use, it would be better to just list out all the rules. When the * alias is used, failures do not list which rule triggered the error:

Using *

invalid.json
  2:3   error  Duplicate object key  json/*
  3:3   error  Comment not allowed   json/*

Using individual rules

invalid.json
  2:3   error  Duplicate object key  json/duplicate-key
  3:3   error  Comment not allowed   json/trailing-comma

Indentation and sort order

Hi any chance I can achieve indentation and/or sorting order check with this plugin? E.g I would like to ensure all my *.json files are sorted alphabetically by keys and has indentation of 1/2/4 spaces/tabs.

Migrate to Github Actions

Travis CI announced a pricing model change in late 2020. While we are likely within the limits of the free tier, its probably just worth moving to Github Actions to keep up with the ecosystem.

What does value-expected?

Hey, I was wondering if value-expected checks, for example for empty strings?
I enabled all checks and added an empty string to my JSON, and it didn't work.

My .eslintrc.json

{
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": ["eslint:recommended"],
    "parserOptions": {
        "ecmaVersion": 13
    },
    "plugins": [
        "json"
    ],
    "rules": {
        "json/json": ["error"]
    }
}

And the part of my JSON with the empty string

"b": {
        "stadt": ["Bamberg", "Bonn", "Böblingen", "Boston", ""],
        "land": ["Belgien", "Brasilien", "Bolivien", "Bermudas", "Bahrain"],
        "fluss": ["Bigge (Deutschland)", "Brahmaputra (u.a. Indien)", "Belaja (Russland)", "Blies (Frankreich und Deutschland)"],
        "name": ["Benjamin", "Benny", "Bernd", "Barbara", "Beate"],
        "beruf": ["Busfahrer", "Beamter", "Bundesminister"],
        "tier": ["Bär", "Biene", "Beluga", "Biber", "Bea", "Bison", "Blaumeise"],
        "marke": ["Basil", "Barbour", "Bench", "Billa Bong", "Blomus", "Bosch", "Braum"],
        "pflanze": ["Berlauch", "Bartlilie"]
    },

Backet misspelling?

CommaOrCloseBacketExpected: 0x205,

I was just doing a spelling audit of my code and I noticed in my eslint config that I had json/comma-or-close-backet-expected.
Should this be bracket instead of backet?
It would be a breaking change to change the name of the rule, but thought I make make an issue anyways to see if perhaps it should be corrected in the next major release.

CHANGELOG missing

I just saw the package is updated to v2.0.0, but I can't find any CHANGELOG to check out the changes.

Would you be so kind to provide us with a decent CHANGELOG please? 🙂

Thanks for all your hard work @azeemba! 🙂

v2: Errors should be reported by default

I was testing the latest version after I made the v2 release and it seems that if the json/json rule is not explicitly set to error in .eslintrc, then no errors are being reported.

@AdrieanKhisbe do you think this should be the default behavior? I think if the extension is enabled, then we should report the errors by default. Users can disable the rules using the ruleIds if they want.

I have unpublished the v2 release for now.

Line 1 always fails with error

I get the following error for every json file, including package.json.

1:1 error Expected an assignment or function call and instead saw an expression no-unused-expressions

I am able to by-pass this error by adding the following line to the top of each file, but I would prefer to understand what the error is or how to suppress it completely

// eslint-disable-next-line no-unused-expressions

Using eslint-plugin-json with create-react-app (ejected)

My application was created using create-react-app, and was also ejected to allow for further customization.

I have installed eslint-plugin-json and included it in my .eslintrc:

{
  "parser": "babel-eslint",
  "extends": [
    "standard",
    "standard-react"
  ],
  "plugins": [
    "babel",
    "json"
  ],
  "env": {
    "browser": true
  },
  "globals": {
    "describe": false,
    "it": false,
    "expect": false
  },
  "rules": {
    "curly": "error",
    "space-before-function-paren": "off",
    "jsx-quotes": ["error", "prefer-single"],
    "semi": ["warn", "always"],
    "no-unused-vars": "warn",
    "spaced-comment": "off",
    "no-debugger": "warn",
    "no-multiple-empty-lines": "warn",
    "no-useless-escape": "off",
    "max-len": ["error", { "code": 120, "tabWidth": 2, "ignoreStrings": true, "ignoreTemplateLiterals": true, "ignoreComments": true }],
    "padded-blocks": "off",
    "react/no-did-update-set-state": "off",
    "key-spacing": "warn"
  }
}

I understand that you are supposed to provide additional "extension" arguments in order to get this to work when running eslint on the command line (e.g. eslint . --ext .json --ext .js)

However I cannot figure out how to get these extra extensions passed to the eslint that is run by the WebpackDevServer. I particularly want the "key-spacing" rule to take effect for JSON files. WebpackDevServer's eslint is properly picking up "key-spacing" violations in JS files, so I know it is properly reading my eslintrc, but is there any way to specify additional eslint file extensions for this use case?

README mentions v1.3.0 but I don't see it on NPM

JSHint was replaced with VSCode's linting implementation in 82e0645. Unfortunately this implementation is asynchronous and eslint is not.

The hack implemented to make this work does not work consistently enough so the published version was removed within minutes of publishing it.

This means that we will have to use the synchronous jsonc-parser that VSCode uses and duplicate a bunch of that logic.

The v1.3 release is pending on this change.

Allow comments in JSON

Firstly, thanks for the great plugin!

In previous versions, comments were allowed (likely as the result of the loose jshint parsing), but in the latest version these are not. As you're now using the jsonc-parser, exposing the option to pass allowComments would be wonderful. 👍

ESLint Rules

Hello,

Apologies in advance if this is a question that has been asked before. Using this plugin is it possible to still load the rules for ESLint? My goal is to turn off the error reporting on duplicate keys

{
    "env": {
        "browser": true
    },
    "extends": "eslint:recommended",
    "plugins": [
        "json"
    ],
    "rules": {
        "no-dupe-keys": "off"
    }
}

It didn't seem to work because the output shows

eslint . --ext .json

403:9  error  Duplicate key 'groupName'  bad-json
404:9  error  Duplicate key 'resources'  bad-json

Combination with eslint-plugin-prettier

Due to the json preprocessor returning an empty string, one can't combine this plugin with eslint-plugin-prettier (prettier only gets an empty string to optimize) for JSON files.

To me it seems like the issue is, that eslint expects us to provide valid JavaScript. One way to circumvent that is by transforming the JSON code to valid JavaScript, for example by returning ['JSON.stringify(%0)\n'.replace('%0', text)] instead. This way prettier would also be able to run over JSON files via eslint.

This is obviously just a hack and also depends on the prettier config in use, but I would propose adding an optional setting to this plugin, which enables a placeholder for JSON->JS conversion. I could also submit a PR.

Update: For further discussion I started PR #39.

Support ESLint 7.x

ESLint v7.0.0 is released 🎉

It would be awesome to have official ESLint 7 support. 👊
I'm happy to help where I can of course 🙂

Column indexes in error reports appear to be incorrect

When running this extension via eslint and linter-eslint in Atom, I am getting errors along the lines of:

Invalid position given by 'json/*'
ESLint returned a point that did not exist in the document being edited.
Rule: `json/*`
Requested start point: 12:16 - 12:18

Taking a simple test file:

{
  test: {
  
  },
}

the plugin returns:

test.json
  2:4  error  Property keys must be doublequoted  json/*
  4:5  error  Trailing comma                      json/*

However I think it should be:

test.json
  2:3  error  Property keys must be doublequoted  json/*
  4:4  error  Trailing comma                      json/*

This fixes the issue with Atom, and also would line up with the column numbers received when I run this in VSCode.

it's not linting at all

I got json like this

{
   "text": "a thing"
   "user": "11"
}

Then I type lint command, it runs , but no error. I was expecting error missing comma

JSON files are ignored by default

It seems eslint ignores .json files by default. It would be helpful if the installation instruction said how to unignore them with a .eslintignore

Error on the first colon.

eslint version: v3.19.0

$ eslint file.json
  1:7  error  Parsing error: Unexpected token :

✖ 1 problem (1 error, 0 warnings)

Where the json is as follows:

{"key": "value"}

TypeError: Cannot read property 'reason' of null

The linter throws an error under the following circumstances"

Example bad_file.json:

{
  "my_string": "hello world"
}
bad_text

Running eslint --ext .json bad_file.json results in the following error

./node_modules/eslint-plugin-json/lib/index.js:39
                    message: error.reason,

TypeError: Cannot read property 'reason' of null
    at ./node_modules/eslint-plugin-json/lib/index.js:39:35
    at Array.map (native)
    at Object.module.exports.processors..json.postprocess (./node_modules/eslint-plugin-json/lib/index.js:35:27)
    at processText (./node_modules/eslint/lib/cli-engine.js:226:30)
    at processFile (./node_modules/eslint/lib/cli-engine.js:270:18)
    at executeOnFile (./node_modules/eslint/lib/cli-engine.js:617:23)
    at Array.forEach (native)
    at CLIEngine.executeOnFiles (./node_modules/eslint/lib/cli-engine.js:640:56)
    at Object.cli.execute (./node_modules/eslint/lib/cli.js:162:95)
    at Object.<anonymous> (./node_modules/eslint/bin/eslint.js:60:20)

Looking at https://github.com/azeemba/eslint-plugin-json/blob/master/lib/index.js#L35 it seems that there are other arguments to the map callback function that could be useful:

{ '0': null,
  '1': 1,
  '2':
   [ { scope: '(main)',
       raw: 'Unrecoverable syntax error.',
       code: 'E041',
       reason: 'Unrecoverable syntax error. (75% scanned).',
       line: 3,
       character: 1 },
     null ] }

@vue/prettier breaks this plugin

If I use this eslint config:

plugins: ["json-files"],
extends: ["@vue/prettier"],

Then this plugin doesn't work. It receives this JSON (added console.log({json}); in editStringJSON()):

{
  json: 'module.exports = {\n' +
    '  "name": "web-watcher",\n' +
    '  "version": "0.2.0",\n' +
    '  "private": true,\n' +
    '  "scripts": {\n' +

Is this something that I should report to @vue/prettier instead?

Documentation link broken

There is a little bug in the README.md file at the end with the following sentence

It is now possible as you can see in the Configuration section

It seems like the link in the Configuration section part is not pointing to an existing section (#configuration). Maybe it was updated?

npm readme gives wrong config format in Usage section

It shows

{
    export default [
      {
        files: ["**/*.json"],
        ...json.configs["recommended"],
    ];
}

...but should be like the format in GitHub readme without missing closing curly brace

export default [
  {
    files: ["**/*.json"],
    ...json.configs["recommended"]
  }
];

Error: Could not serialize processor object (missing 'meta' object)

With eslint 9+ i het this error using eslint-plugin-json with flat config

Oops! Something went wrong! :(

ESLint: 9.6.0

Error: Could not serialize processor object (missing 'meta' object).
    at Object.value (C:\code\test_eslint_with_json\node_modules\eslint\lib\config\flat-config-array.js:390:27)
    at stringify (C:\code\test_eslint_with_json\node_modules\json-stable-stringify-without-jsonify\index.js:25:25)
    at module.exports (C:\code\test_eslint_with_json\node_modules\json-stable-stringify-without-jsonify\index.js:68:7)
    at hashOfConfigFor (C:\code\test_eslint_with_json\node_modules\eslint\lib\cli-engine\lint-result-cache.js:50:75)
    at LintResultCache.getCachedLintResults (C:\code\test_eslint_with_json\node_modules\eslint\lib\cli-engine\lint-result-cache.js:116:30)
    at C:\code\test_eslint_with_json\node_modules\eslint\lib\eslint\eslint.js:903:41
    at Array.map (<anonymous>)
    at ESLint.lintFiles (C:\code\test_eslint_with_json\node_modules\eslint\lib\eslint\eslint.js:882:23)
    at async Object.execute (C:\code\test_eslint_with_json\node_modules\eslint\lib\cli.js:521:23)
    at async main (C:\code\test_eslint_with_json\node_modules\eslint\bin\eslint.js:153:22)

eslint lib/config/flat-config-array.js expect processors to have meta object
https://eslint.org/docs/latest/extend/custom-processors

const processors = {
    // Supports old config.
    '.json': jsonProcessor,
    // Supports new config.
    json: jsonProcessor,
};

Skip large files

Hi! Thanks for your very useful plugin.
Could you add a way to make it skip files larger than a defined limit?

Ability to customize JSHint rules

Everything from JSHint, including warnings, gets treated as an error by eslint. It would be great to be able to turn off certain rules.

For example, I'm trying to lint json files that contain locale data. There are warnings This character may get silently deleted by one or more browsers for languages that include diacritical marks (combined characters). Given the browsers we target, this is not something that I want as a failure, however - everything from the plugin is treated as a failure by eslint. I added a .jshintrcfile, but it's ignored by the plugin.

Is there already a way to do this that I missed?

How do you get this to work?

I have a config file like this:

.eslintrc.js
module.exports = {
  root: true,

  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 2018,
    sourceType: 'module',
  },

  env: {
    browser: true,
    node: true,
    es2017: true,
  },

  plugins: [
    'json', // doesn't seem to do anything with JSON files
    'promise', // https://github.com/xjamundx/eslint-plugin-promise
    'html',
  ],

  extends: [
    // Uses the recommended rules from the @typescript-eslint/eslint-plugin
    'plugin:@typescript-eslint/recommended',
    // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
    'prettier/@typescript-eslint',
    'plugin:json/recommended',
    // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
    'plugin:prettier/recommended',
  ],

  // add your custom rules here
  rules: {
    'no-debugger': 'error',
    'prefer-const': 'error',
    'one-var': ['error', 'never'],
    'no-var': 'error',
    'no-return-assign': ['error', 'except-parens'],
    'brace-style': ['error', '1tbs', {allowSingleLine: false}],
    'quote-props': ['error', 'as-needed'],
    curly: ['error', 'multi-or-nest', 'consistent'],

    // --- PROMISE ---------------------------------
    // from https://github.com/xjamundx/eslint-plugin-promise

    'promise/always-return': 'off',
    'promise/no-return-wrap': 'error',
    'promise/param-names': 'error',
    'promise/catch-or-return': 'error',
    'promise/no-new-statics': 'error',
    'promise/no-return-in-finally': 'error',

    // --- TYPESCRIPT ------------------------------

    'no-undef': 0,
    'no-unused-vars': 0,

    '@typescript-eslint/naming-convention': 'off', // — Require community JS/TS variable naming conventions. TODO, this one has lots of options.
    '@typescript-eslint/adjacent-overload-signatures': 'error', // — Require that member overloads be consecutive
    '@typescript-eslint/explicit-function-return-type': 'error', // — Require explicit return types on functions and class methods
    '@typescript-eslint/explicit-module-boundary-types': 'off', // — Require explicit types on all things that are exported from modules. Off because we handle this with the explicit-function-return-type rule paired with (soon) the noImplicitAny option in tsconfig.
    '@typescript-eslint/consistent-type-assertions': 'error', // — Enforces the use of `as` Type assertions instead of <Type> assertions.
    '@typescript-eslint/no-array-constructor': 'error', // — Disallow generic Array constructors
    '@typescript-eslint/no-explicit-any': 'off', // — Disallow usage of the any type
    '@typescript-eslint/no-inferrable-types': 'off', // — Disallows explicit type declarations for variables or parameters initialized to a number, string, or boolean.
    '@typescript-eslint/no-namespace': 'off', // — Disallow the use of custom TypeScript modules and namespaces
    '@typescript-eslint/triple-slash-reference': 'error', // — Disallow /// <reference path="" /> comments
    '@typescript-eslint/no-unused-vars': 'off', // — Off beacuse TypeScript gives us these errors already.
    '@typescript-eslint/no-var-requires': 'off', // — Disallows the use of require statements except in import statements
    '@typescript-eslint/type-annotation-spacing': ['error', {}], // — Require consistent spacing around type annotations
    '@typescript-eslint/no-non-null-assertion': 'off', // — Prevents non-null assertiong with `!`
  },

  settings: {},
}

And then I try to run

eslint package.json

and it finishes without outputting anything to console, regardless of what format I have in my package.json.


I've tried getting eslint-plugin-json to work a few times over the past couple years, over several versions of eslint, but it always seems not to do anything.

Consider approach used in eslint-plugin-json-format

I couldn't use this module since the dependencies just don't make sense for running in CI, so I made eslint-plugin-json-format. You should consider adopting the strategy I use there.

If you don't feel like maintaining this or don't want to improve it, I'd be happy to take the eslint-plugin-json package name 😉

Also let me know any caveats you notice with my plugin compared to this one

Support ESLint 8.x

ESLint v8.0.0 is released 🎉

It would be awesome to have official ESLint 8 support. 👊
I'm happy to help where I can of course 🙂

Is it possible to use this plugin/parser to make our own custom rules?

I'm not sure if it is currently possible, but it would be awesome if we were able to use this plugin as a parser for implementing our own custom json-based rules.

When googling, there is another project that is supposedly an eslint json parser, but it is built on eslint/espree, so may have the issues mentioned in your readme

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.