Giter Club home page Giter Club logo

jsonlint's Introduction

JSON Lint

A pure JavaScript version of the service provided at jsonlint.com.

Command line interface

Install jsonlint with npm to use the command line interface:

npm install jsonlint -g

Validate a file like so:

jsonlint myfile.json

or pipe input into stdin:

cat myfile.json | jsonlint

jsonlint will either report a syntax error with details or pretty print the source if it is valid.

Options

$ jsonlint -h

Usage: jsonlint [file] [options]

file     file to parse; otherwise uses stdin

Options:
   -v, --version            print version and exit
   -s, --sort-keys          sort object keys
   -i, --in-place           overwrite the file
   -t CHAR, --indent CHAR   character(s) to use for indentation  [  ]
   -c, --compact            compact error display
   -V, --validate           a JSON schema to use for validation
   -e, --environment        which specification of JSON Schema the validation file uses  [json-schema-draft-03]
   -q, --quiet              do not print the parsed json to STDOUT  [false]
   -p, --pretty-print       force pretty printing even if invalid

Module interface

I'm not sure why you wouldn't use the built in JSON.parse but you can use jsonlint from a CommonJS module:

var jsonlint = require("jsonlint");

jsonlint.parse('{"creative?": false}');

It returns the parsed object or throws an Error.

Vim Plugins

MIT License

Copyright (C) 2012 Zachary Carter

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

jsonlint's People

Contributors

diurnalist avatar fjakobs avatar gregglind avatar louismrose avatar lroggendorff avatar millermedeiros avatar reiz avatar rhysd avatar saaguero avatar strugee avatar tmcw avatar umbrae avatar willemarcel avatar zaach 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  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

jsonlint's Issues

In-place overwrite with pretty-printed JSON

Instead of outputting the pretty-printed JSON on stdout, have an option to simply re-write the file in question with the pretty-printed JSON data. (Mainly useful in precommit-hooks and other automation tools.)

Perhaps via an -i / --in-place option, per sed.

Large (long) integers incorrectly parsed

Input to http://zaach.github.io/jsonlint/ : {"fooId":1111111111258928239}
Output:
{
"fooId": 1111111111258928300
}

Somehow the 239 in the last 3 digits becomes 300. The input integer fits within 64 bits (long type in Java). The issue is reproducible with different values and it is always the last few digits which are different. This has not been an issue for small integers (2-3 digits).

Thanks!

Multiple files support

Hello,
I'd like to ask you to implement (and document) support for specifying multiple input files. That would allow us to run jsonlint from build (e.g. npm) scripts since we would like to pass the list of the files to lint from an environment variable. There is actually a lot of linters that accept multiple files already.

[Solved] Global install with npm doesn't work.

When I try to use jsonlint after a global install i get:

module.js:340
throw err;
^
Error: Cannot find module 'jsonlint'

When using the project/local install (without -g) everything works as it should.

Am I doing something wrong?

When doing a global install i get this:
$ sudo npm install jsonlint -g
npm http GET https://registry.npmjs.org/jsonlint
npm http 304 https://registry.npmjs.org/jsonlint
npm http GET https://registry.npmjs.org/nomnom
npm http GET https://registry.npmjs.org/JSV
npm http 304 https://registry.npmjs.org/nomnom
npm http 304 https://registry.npmjs.org/JSV
npm http GET https://registry.npmjs.org/underscore
npm http GET https://registry.npmjs.org/colors
npm http 304 https://registry.npmjs.org/colors
npm http 304 https://registry.npmjs.org/underscore
/usr/local/bin/jsonlint -> /usr/local/lib/node_modules/jsonlint/lib/cli.js
[email protected] /usr/local/lib/node_modules/jsonlint
├── [email protected]
└── [email protected] ([email protected], [email protected])

No errors whilst installing as you can see, just when running as above.

---EDIT------------------------------------------------------------------------

Sorry for shouting without cause, further googeling showed me the answer:

$ export NODE_PATH='/usr/local/lib/node_modules'

After this I had no more issues.

However could the install script check if there is a NODE_PATH set and warn if not that would help others like me in the future.

Don't join with CWD

[jga] ~: jsonlint /tmp/test.json 

node.js:134
        throw e; // process.nextTick error, or 'error' event on first tick
        ^
Error: EBADF, Bad file descriptor '/home/jga/tmp/test.json'
    at Object.openSync (fs.js:221:18)
    at Object.readFileSync (fs.js:112:15)
    at main (/usr/lib/node_modules/jsonlint/lib/cli.js:53:23)
    at Object.<anonymous> (/usr/lib/node_modules/jsonlint/lib/cli.js:93:1)
    at Module._compile (module.js:411:26)
    at Object..js (module.js:417:10)
    at Module.load (module.js:343:31)
    at Function._load (module.js:302:12)
    at Array.<anonymous> (module.js:430:10)
    at EventEmitter._tickCallback (node.js:126:26)

enh: quiet mode

I am using this as my builder / linter in Sublime Text 2. It would be helpful to have a '-q' option, so I can just see the errors. (In my case, just redirecting to '/dev/null' isn't an option.

Recipe for the curious:

{
    "cmd": ["jsonlint", "$file"],
    "selector": "source.json",
    "path": "/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin"
}

Unescaped Unicode Characters Not Detected

I had an app that was giving unterminated string constant exceptions in jQuery/Firefox and Illegal Character exceptions in jQuery/Chrome. I ran my JSON content through JSONLint and it reported the content as valid.

After looking into it, I found that my JSON had unescaped unicode characters (smart quotes).

I modified my code to escape unicode chars in the format \uxxxx and my app is now working.

So, it looks like jsonlint is passing as correct JSON content that has unicode and that's not correct.

Accept input from stdin

I want to be able to pipe a curl request into this awesome package

like

$curl http://API/ping.js |jsonlint

-s option doesn't sort object keys

-s option doesn't sort keys in the below example. 'jsonlint -s testcase.json' returns the same json as input. Obviously, "w" should follow "a".

--- testcase.json ---
[[{
"w": "",
"a": 4
}]]

version 1.6.0

JSON Output

Hi,

Really dig your module, however when I tried to use in my module and output the json via console.log I got the following outputs:

WebserverCPUAlarmHigh: { Type: 'AWS::CloudWatch::Alarm', Properties: [Object] },
WebserverCPUAlarmLow: { Type: 'AWS::CloudWatch::Alarm', Properties: [Object] } },

Notice the [Object] portion... Not sure why its not outputting straight json?

Here's my code: https://gist.github.com/Hesse/6513835

Duplicate keys aren't cool!

$ echo '{"a":1,"a":2}' | jsonlint
The "sys" module is now called "util". It should have a similar interface.
{
  "a": 2
}
$ 

Normalize pretty-printed JSON

For various reasons, I'd quite like the pretty-printed JSON to have it's object-keys sorted on output (mainly sane diff'ing). Either optionally or forced (like Python's json-module).

Add an option for C-style braces

Please add an option for C-style object and array braces.

Java-style (current):

{
    "foo" : {
        "bar" : 10
    },
    "lol" : [
        "rofl",
        "lmao"
    ]
}

C-style:

{
    "foo" :
    {
        "bar" : 10
    },
    "lol" :
    [
        "rofl",
        "lmao"
    ]
}

JSON-style array inside quotes parsed as arrays.

Strings which look like JSON arrays are parsed as arrays (and will throw an error.)

For example:
"pos": "[106.675,525.792,47.7364]" is entirely valid JSON but will error out with Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[' when linted.

Tag the new released versions

Hi, it seems that jsonlint is already v1.6.2 now.
Would you like to add tags for the new released versions?
Thank you!

Prettier error messages

Right now the default error messages are pretty hard to parse by humans. It would be great if the error messages could be a bit friendlier, such as:

The 'foo' property is missing and is required.

Or

The 'foo' property should be a string but is a number.

Printing Location of Schema error possible?

Is it possible to output the line number of line of a place where the schema error occured?
If that is possible, then it can be parsed by the text editors to show where
user mistakingly typed an error, resulting more ease on editing the text...

Cannot browserify jsonlint: module "file" missing

Thanks for offering jsonlint via npm, works great.

I stumbled upon one issue though: when I try to browserify jsonlint, an error is thrown:

Error: Cannot find module 'file' from '/home/ubuntu/workspace/node_modules/jsonlint/lib'

The module file is required here in the source code:
https://github.com/zaach/jsonlint/blob/master/lib/jsonlint.js#L424

It looks like the "file" module is missing from the dependencies in package.json. But maybe this code is redundant anyway: I guess if you're not running node.js (i.e. typeof process === 'undefined'), the file module won't work either?

browser version

right now if you use import jsonlint from 'jsonlint'; e.g. via browserify/babel it doesn't have an export -- there's no export statement in web/ folder

Object error in IE 11

I'm using the checker under web/
In Internet Explorer 11, if you paste this text
::
{

"Accept-Language": "en-US,en;q=0.8"

"Host": "headers.jsontest.com",

"Accept-Charset": "ISO-8859-1,utf-8;q=0.7,;q=0.3",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,
/*;q=0.8"
}

you get an [Object error], instead of a parse fail.

support for schema verion 04

Hello,

  1. which json-schema-draft versions are supported?
  2. could you please add support for json-schema-draft-04?
    (where in the code is it configured?)

--pretty-print option always exits with status 0, even if input is invalid json

If you give jsonlint the --pretty-print option with invalid json, then jsonlint prints an error message (good), outputs its best guess at formatted json (good), but exits with status 0 (bad). Perhaps this means that the parsing succeeded, but this makes it difficult to detect whether the input is valid json.

Expected behavior: exit status is 0 if input valid json, 1 otherwise.

(jsonlint 1.6.0, node v 0.10.0 on OS X 10.6.8)

tab inside string value is not handled correctly

example:

{
"action": "log in"
}

output:

Error: Parse error on line 2:
{ "action": "log in"}
---------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'

expected output:

JSON is valid!

No licensing/copyright information

I can't seem to find licensing information for this package anywhere. Something like BSD would be great, but of course that's up to you, as long as the terms are clear.

reformat JSON error

  1. paste the following code to jsonlint

    {
      "s": "\\"
    }
  2. make sure the checkbox reformat JSON is checked, then click validate button many times

The backslash will continue to repeat itself

Piping to head causes error

The following console interaction should explain the issue.

$ curl http://host/file.json | jsonlint | head -4
{
  "some-key": "some-value",
  "array": [
    {

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: write EPIPE
    at errnoException (net.js:904:11)
    at Object.afterWrite (net.js:720:19)

Is there a way to know that the closed output pipe is not an error?

Problems recognizing and/or reformatting escapes

I've noticed a couple of issues in the reformatted output when there's escapes in the input:

  1. disappearing slashes. This represents a two-character string, not a newline escape:

    • in: "\\n"
    • expected out: "\\n"
    • actual out: "\n"

    This also happens for b, r, f, and t.

  2. unexpected slashes.

    • in: "\u0066"
    • expected out: "f" (or "\u0066")
    • actual out: "\\u0066"

Don't write back empty JSON files with --in-place

diff --git a/lib/cli.js b/lib/cli.js
index 068fcf1..dce6845 100755
--- a/lib/cli.js
+++ b/lib/cli.js
@@ -47,14 +47,20 @@ function parse (source) {
 }

 function main (args) {
-  var source = '';
+  var source = '',
+      parsedSource = '';
    if (options.file) {
     var path = require('path').join(process.cwd(), options.file); 
     source = fs.readFileSync(path, "utf8");
+    parsedSource = parse(source);
     if (options.inplace) {
-      fs.writeSync(fs.openSync(path,'w+'), parse(source), 0, "utf8");
+      if (parsedSource) {
+        fs.writeSync(fs.openSync(path,'w+'), parsedSource, 0, "utf8");
+      } else {
+        sys.error("JSON contained errors - not overwriting file");
+      }
     } else {
-      sys.puts(parse(source));
+      sys.puts(parsedSource);
     }
   } else {
     var stdin = process.openStdin();

It's slightly more complicated as I'd like to write an error message, but it seem the parser kills the program right away on errors. But if I don't check if the parser acutally returned anything, it writes out an empty file...

Should accept a folder/glob as an argument

I'd love to lint multiple json files in a single go, and get a report of each failure, but: jsontlint project/**/*.json doesn't seem to do the job. When linting multiple files it'd probably make sense to not output pretty-printed json when a file passes - simply return the errors.

What do you think?

why don't you allow "values"?

The website http://jsonlint.com/ says it is based on this library. However, that site has the following bug: it rejects valid JSON that is NOT an object or an array. These strings are all valid JSON:

1
12
12.34
"string"
true
false
null

Should this be corrected in this library?

Accept pull requests?

I was looking over the issues and was planning to send some pull requests but when i realized there were issues from 2011 I wanted to be sure they would be looked at before giving an attempt.

npm WARN [email protected]

npm WARN [email protected] dependencies field should be hash of : pairs
/usr/local/bin/jsonlint -> /usr/local/lib/node_modules/jsonlint/lib/cli.js
[email protected] /usr/local/lib/node_modules/jsonlint
└── [email protected]

I am having this warning message at the end of jsonlint installation. Although that message jsonlint seems to be working fine. But again I would like to learn what it is.

Thanks.

Please show where the error happends

Please show where the error happens and what should be there instead. Because currently it says json error at this file. there is no line or what to replace instead.

Ability to lint files w/ JSON comments

I'm trying to lint some JSON files that happen to have some comments in JSON like this:

// this is configuration specific to aws deployments
{
  // disable statsd for aws
  "statsd": {
    "enabled": false
  }
}

But the $ jsonlint config/aws.json command gives me the following:

$ jsonlint config/aws.json
[Error: Parse error on line 1:
// this is configura
^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined']

I'm not sure what libs mozilla/persona is using to load the commented JSON, but a bunch of the files are failing jsonlint due to the comments.

--quiet + STDIN never gives errors and exits with exitcode 0

Quiet + file:

$ echo "{ 'single-quoted': 'thus-bad-json' }" > /tmp/bad.json
$ jsonlint -c -q /tmp/bad.json ; echo $?
/tmp/bad.json: line 1, col 1, found: 'INVALID' - expected: 'STRING', '}'.
1

Quiet + STDIN:

$ echo "{ 'single-quoted': 'thus-bad-json' }" | jsonlint -c -q -; echo $?
0

Resolved with following patch:

--- /usr/local/bin/jsonlint.orig        2013-11-28 11:43:41.000000000 +0100
+++ /usr/local/bin/jsonlint     2013-11-28 11:44:48.000000000 +0100
@@ -147,7 +147,8 @@ function main (args) {
       source += chunk.toString('utf8');
     });
     stdin.on('end', function () {
-      if (! options.quiet) {console.log(parse(source))};
+      source = parse(source);
+      if (! options.quiet) {console.log(source)};
     });
   }
 }

Behaviour after patch:

$ echo "{ 'single-quoted': 'thus-bad-json' }" | jsonlint -c -q -; echo $?
line 1, col 1, found: 'INVALID' - expected: 'STRING', '}'.
1

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.