48 Commits

Author SHA1 Message Date
Zachary Carter
fca1f5f846 1.6.0 2013-04-02 10:44:25 -07:00
Zach Carter
f019341e15 Merge pull request #30 from teknogeek0/85bf286c795eeef6d17f1c89b646a94b5623e385
Add in the -q/--quiet option to the README.md so folks know its there.
2013-04-01 21:43:59 -07:00
Christopher Munns
85bf286c79 Adding in the -q/--quiet option to the Readme.md 2013-04-01 21:39:15 -04:00
Zach Carter
79b553fb65 Merge pull request #27 from lroggendorff/add-forceformat-option
Add forceformat option
2012-12-16 11:04:07 -08:00
Lance Roggendorff
59c36ad370 Merge branch 'fix-inplace-overwriting' into add-forceformat-option
* fix-inplace-overwriting:
  Fixing variable name when overwriting input file.
2012-09-12 23:12:25 -05:00
Lance Roggendorff
92ac817d17 Adding forceformat option: format invalid output just like jsonlint.com
When using jsonlint.com, even invalid JSON is pretty printed. It seemed
like a good option to have in the cli version as well. This is simply
inserting the char-by-char formatter from
https://github.com/umbrae/jsonlintdotcom and adding an option to cli.js.
2012-09-12 23:11:11 -05:00
Lance Roggendorff
0f3202370f Fixing variable name when overwriting input file.
It looks like at one time the variable referencing the input file was
'path', and later on it was changed to 'json', but the if
(options.inplace) block was never updated.
2012-09-12 22:55:26 -05:00
Zachary Carter
1d7ed8ab13 1.5.1 2012-08-22 10:37:25 -07:00
Zach Carter
5e02f8b8e0 Merge pull request #26 from gregglind/quiet25
added quiet mode #25
2012-08-22 10:34:16 -07:00
Gregg Lind
f2e1de3039 added quiet mode 2012-08-22 09:10:54 -05:00
Zach Carter
cdb7737033 Update master 2012-06-19 20:44:54 -07:00
Zachary Carter
5c5ad5acf0 1.5.0 2012-05-28 15:14:43 -07:00
Zachary Carter
6af4143235 add schema validation 2012-05-28 15:14:09 -07:00
Zachary Carter
cb82cc205d 1.4.1 2012-05-28 12:30:28 -07:00
Zachary Carter
3899996991 update bundle script 2012-05-28 12:30:05 -07:00
Zachary Carter
14a108f3a4 fix escaping of special characters (issue #22) 2012-05-28 12:27:08 -07:00
Zachary Carter
c07fb3db3b 1.4.0 2012-05-27 14:34:50 -07:00
Zachary Carter
f88c4842ff fix Makefile 2012-05-27 14:34:29 -07:00
Zachary Carter
eca60bb22b update grammar for latest jison 2012-05-27 14:26:14 -07:00
Zachary Carter
4f24c338fa fix escaping bug with backslashes 2012-05-27 14:25:28 -07:00
Zachary Carter
f4d68f8fd1 Merge branch 'master' of github.com:zaach/jsonlint 2012-05-27 12:51:26 -07:00
Zach Carter
9eb4bd8260 add vim plugins 2012-05-27 12:41:24 -07:00
Zachary Carter
11e7192a72 appease jslint 2012-05-15 21:42:25 -07:00
Zachary Carter
c42d2abffc 1.3.2 2012-05-15 19:53:48 -07:00
Zachary Carter
ee5c2d557c use stderr for errors 2012-05-15 19:53:35 -07:00
Zach Carter
2e869ca7ec Merge branch 'master' of github.com:zaach/jsonlint 2012-05-15 22:14:10 -04:00
Zach Carter
833a75648f MIT License 2012-05-15 19:04:46 -07:00
Zach Carter
efd1ae6071 1.3.1 2012-04-17 15:06:44 -04:00
Zach Carter
0653b731db update nomnom 2012-04-05 22:18:27 -04:00
Zach Carter
5cca03512e fix issue #16, normalize path 2012-04-05 22:13:44 -04:00
Zach Carter
4c65154163 Remove comment about top level primitives 2012-04-05 22:14:20 -03:00
Zach Carter
c21e8eb8de update version 2011-12-17 19:51:52 -05:00
Zach Carter
6d09e77ef9 Merge pull request #15 from millermedeiros/master
added compact output option to allow integrating into IDEs more easily (like Vim)
2011-12-17 16:48:38 -08:00
millermedeiros
1956caa5a4 add compact option to CLI and update flags to work with latest nomnom api. see #10 2011-12-16 13:45:52 -02:00
Zach Carter
5a52ba4662 change sys module to util 2011-11-21 20:19:34 -05:00
Zach Carter
1ff64514b6 update for node 0.6 2011-11-10 12:32:38 -05:00
Zach Carter
19fd9a63d2 Merge pull request #9 from fjakobs/patch-1
fix typo
2011-06-19 13:27:12 -07:00
Fabian Jakobs
36370390e0 fix typo 2011-06-19 13:11:46 -07:00
Zach Carter
cdd45ca8ad version 1.2.0 2011-06-12 13:42:05 -04:00
Zach Carter
348eeb4c11 Follow spec instead of rfc for top level strings/numbers/null/booleans 2011-06-12 13:40:39 -04:00
Zach Carter
acf3cd47bc Merge branch 'master' of github.com:zaach/jsonlint 2011-06-04 10:33:02 -04:00
Zach Carter
cfda950c3c version 1.1.1 2011-06-04 10:32:18 -04:00
Zach Carter
ae5025e5ac Fix overwriting bug. 2011-06-04 10:32:04 -04:00
Zach Carter
77766eeae9 Note command-line options in the readme 2011-06-01 16:09:35 -07:00
Zach Carter
280ccc5121 version 1.1.0 2011-06-01 17:56:38 -04:00
Zach Carter
f08f1b245f add option to sort object keys 2011-06-01 17:55:58 -04:00
Zach Carter
7d7e4b499f allow inplace overwrite 2011-06-01 17:42:36 -04:00
Zach Carter
26d697c45f Add nomnom for option parsing. Allow indentation option" 2011-06-01 17:24:24 -04:00
12 changed files with 438 additions and 114 deletions

View File

@@ -1,11 +1,17 @@
all: build test
all: build test site
build:
jison src/jsonlint.y src/jsonlint.l
mv jsonlint.js lib/jsonlint.js
node scripts/bundle.js | uglifyjs > web/jsonlint.js
site:
cp web/jsonlint.js ../jsonlint-pages/jsonlint.js
deploy: site
cd ../jsonlint-pages && git commit -a -m 'deploy site updates' && git push origin gh-pages
test: lib/jsonlint.js test/all-tests.js
node test/all-tests.js

View File

@@ -1,7 +1,7 @@
JSON Lint
=========
A pure [JavaScript version](http://zaach.github.com/jsonlint/) of the service provided at [jsonlin.com](http://jsonlint.com).
A pure [JavaScript version](http://zaach.github.com/jsonlint/) of the service provided at [jsonlint.com](http://jsonlint.com).
## Command line interface
Install jsonlint with npm to use the command line interface:
@@ -18,6 +18,25 @@ or pipe input into stdin:
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
-q, --quiet do not print the parsed json to STDOUT
## 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:
@@ -27,3 +46,18 @@ I'm not sure why you wouldn't use the built in `JSON.parse` but you can use json
jsonlint.parse('{"creative?": false}');
It returns the parsed object or throws an `Error`.
## Vim Plugins
* [Syntastic](http://www.vim.org/scripts/script.php?script_id=2736)
* [sourcebeautify](http://www.vim.org/scripts/script.php?script_id=4079)
## 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.

View File

@@ -1,22 +1,144 @@
#!/usr/bin/env node
var sys = require("sys");
var fs = require("fs");
var path = require("path");
var parser = require("./jsonlint").parser;
var JSV = require("JSV").JSV;
var formatter = require("./formatter.js").formatter;
var options = require("nomnom")
.script("jsonlint")
.options({
file: {
position: 0,
help: "file to parse; otherwise uses stdin"
},
version: {
flag : true,
string: '-v, --version',
help: 'print version and exit',
callback: function() {
return require("../package").version;
}
},
sort : {
flag : true,
string: '-s, --sort-keys',
help: 'sort object keys'
},
inplace : {
flag : true,
string: '-i, --in-place',
help: 'overwrite the file'
},
indent : {
string: '-t CHAR, --indent CHAR',
"default": " ",
help: 'character(s) to use for indentation'
},
compact : {
flag : true,
string: '-c, --compact',
help : 'compact error display'
},
validate : {
string: '-V, --validate',
help : 'a JSON schema to use for validation'
},
env : {
string: '-e, --environment',
"default": "json-schema-draft-03",
help: 'which specification of JSON Schema the validation file uses'
},
quiet: {
flag: true,
key: "value",
string: '-q, --quiet',
"default": false,
help: 'do not print the parsed json to STDOUT'
},
forcePrettyPrint: {
flag: true,
string: '-p, --pretty-print',
help: 'force pretty printing even if invalid'
}
}).parse();
if (options.compact) {
var fileName = options.file? options.file + ': ' : '';
parser.parseError = parser.lexer.parseError = function(str, hash) {
console.error(fileName + 'line '+ hash.loc.first_line +', col '+ hash.loc.last_column +', found: \''+ hash.token +'\' - expected: '+ hash.expected.join(', ') +'.');
throw new Error(str);
};
}
function parse (source) {
var parsed,
formatted;
try {
sys.puts(JSON.stringify(parser.parse(source),null," "));
parsed = options.sort ?
sortObject(parser.parse(source)) :
parser.parse(source);
if (options.validate) {
var env = JSV.createEnvironment(options.env);
var schema = JSON.parse(fs.readFileSync(path.normalize(options.validate), "utf8"));
var report = env.validate(parsed, schema);
if (report.errors.length) {
throw report.errors.reduce(schemaError, 'Validation Errors:');
}
}
return JSON.stringify(parsed,null,options.indent);
} catch (e) {
sys.puts(e);
process.exit(1);
if ( options.forcePrettyPrint ) {
/* From https://github.com/umbrae/jsonlintdotcom:
* If we failed to validate, run our manual formatter and then re-validate so that we
* can get a better line number. On a successful validate, we don't want to run our
* manual formatter because the automatic one is faster and probably more reliable.
*/
try {
formatted = formatter.formatJson(source, options.indent);
// Re-parse so exception output gets better line numbers
parsed = parser.parse(formatted);
} catch (e) {
if (! options.compact) {
console.error(e);
}
return formatted;
process.exit(1);
}
} else {
if (! options.compact) {
console.error(e);
}
process.exit(1);
}
}
}
function schemaError (str, err) {
return str +
"\n\n"+err.message +
"\nuri: " + err.uri +
"\nschemaUri: " + err.schemaUri +
"\nattribute: " + err.attribute +
"\ndetails: " + JSON.stringify(err.details);
}
function main (args) {
var source = '';
if (args[1]) {
source = require('fs').readFileSync(require('path').join(process.cwd(), args[1]), "utf8");
parse(source);
if (options.file) {
var json = path.normalize(options.file);
source = parse(fs.readFileSync(json, "utf8"));
if (options.inplace) {
fs.writeSync(fs.openSync(json,'w+'), source, 0, "utf8");
} else {
if (! options.quiet) { console.log(source)};
}
} else {
var stdin = process.openStdin();
stdin.setEncoding('utf8');
@@ -25,9 +147,32 @@ function main (args) {
source += chunk.toString('utf8');
});
stdin.on('end', function () {
parse(source);
if (! options.quiet) {console.log(parse(source))};
});
}
}
// from http://stackoverflow.com/questions/1359761/sorting-a-json-object-in-javascript
function sortObject(o) {
if (Object.prototype.toString.call(o) !== '[object Object]') {
return o;
}
var sorted = {},
key, a = [];
for (key in o) {
if (o.hasOwnProperty(key)) {
a.push(key);
}
}
a.sort();
for (key = 0; key < a.length; key++) {
sorted[a[key]] = sortObject(o[a[key]]);
}
return sorted;
}
main(process.argv.slice(1));

92
lib/formatter.js Normal file
View File

@@ -0,0 +1,92 @@
#!/usr/bin/env node
/**
* Manual formatter taken straight from https://github.com/umbrae/jsonlintdotcom
**/
/*jslint white: true, devel: true, onevar: true, browser: true, undef: true, nomen: true, regexp: true, plusplus: false, bitwise: true, newcap: true, maxerr: 50, indent: 4 */
/**
* jsl.format - Provide json reformatting in a character-by-character approach, so that even invalid JSON may be reformatted (to the best of its ability).
*
**/
var formatter = (function () {
function repeat(s, count) {
return new Array(count + 1).join(s);
}
function formatJson(json, indentChars) {
var i = 0,
il = 0,
tab = (typeof indentChars !== "undefined") ? indentChars : " ",
newJson = "",
indentLevel = 0,
inString = false,
currentChar = null;
for (i = 0, il = json.length; i < il; i += 1) {
currentChar = json.charAt(i);
switch (currentChar) {
case '{':
case '[':
if (!inString) {
newJson += currentChar + "\n" + repeat(tab, indentLevel + 1);
indentLevel += 1;
} else {
newJson += currentChar;
}
break;
case '}':
case ']':
if (!inString) {
indentLevel -= 1;
newJson += "\n" + repeat(tab, indentLevel) + currentChar;
} else {
newJson += currentChar;
}
break;
case ',':
if (!inString) {
newJson += ",\n" + repeat(tab, indentLevel);
} else {
newJson += currentChar;
}
break;
case ':':
if (!inString) {
newJson += ": ";
} else {
newJson += currentChar;
}
break;
case ' ':
case "\n":
case "\t":
if (inString) {
newJson += currentChar;
}
break;
case '"':
if (i > 0 && json.charAt(i - 1) !== '\\') {
inString = !inString;
}
newJson += currentChar;
break;
default:
newJson += currentChar;
break;
}
}
return newJson;
}
return { "formatJson": formatJson };
}());
if (typeof require !== 'undefined' && typeof exports !== 'undefined') {
exports.formatter = formatter;
}

View File

@@ -2,14 +2,22 @@
var jsonlint = (function(){
var parser = {trace: function trace() { },
yy: {},
symbols_: {"error":2,"JSONString":3,"STRING":4,"JSONNumber":5,"NUMBER":6,"JSONNullLiteral":7,"NULL":8,"JSONBooleanLiteral":9,"TRUE":10,"FALSE":11,"JSONText":12,"JSONObject":13,"EOF":14,"JSONArray":15,"JSONValue":16,"{":17,"}":18,"JSONMemberList":19,"JSONMember":20,":":21,",":22,"[":23,"]":24,"JSONElementList":25,"$accept":0,"$end":1},
symbols_: {"error":2,"JSONString":3,"STRING":4,"JSONNumber":5,"NUMBER":6,"JSONNullLiteral":7,"NULL":8,"JSONBooleanLiteral":9,"TRUE":10,"FALSE":11,"JSONText":12,"JSONValue":13,"EOF":14,"JSONObject":15,"JSONArray":16,"{":17,"}":18,"JSONMemberList":19,"JSONMember":20,":":21,",":22,"[":23,"]":24,"JSONElementList":25,"$accept":0,"$end":1},
terminals_: {2:"error",4:"STRING",6:"NUMBER",8:"NULL",10:"TRUE",11:"FALSE",14:"EOF",17:"{",18:"}",21:":",22:",",23:"[",24:"]"},
productions_: [0,[3,1],[5,1],[7,1],[9,1],[9,1],[12,2],[12,2],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[13,2],[13,3],[20,3],[19,1],[19,3],[15,2],[15,3],[25,1],[25,3]],
productions_: [0,[3,1],[5,1],[7,1],[9,1],[9,1],[12,2],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[15,2],[15,3],[20,3],[19,1],[19,3],[16,2],[16,3],[25,1],[25,3]],
performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) {
var $0 = $$.length - 1;
switch (yystate) {
case 1:this.$ = yytext;
case 1: // replace escaped characters with actual character
this.$ = yytext.replace(/\\(\\|")/g, "$"+"1")
.replace(/\\n/g,'\n')
.replace(/\\r/g,'\r')
.replace(/\\t/g,'\t')
.replace(/\\v/g,'\v')
.replace(/\\f/g,'\f')
.replace(/\\b/g,'\b');
break;
case 2:this.$ = Number(yytext);
break;
@@ -21,42 +29,28 @@ case 5:this.$ = false;
break;
case 6:return this.$ = $$[$0-1];
break;
case 7:return this.$ = $$[$0-1];
case 13:this.$ = {};
break;
case 8:this.$ = $$[$0];
case 14:this.$ = $$[$0-1];
break;
case 9:this.$ = $$[$0];
case 15:this.$ = [$$[$0-2], $$[$0]];
break;
case 10:this.$ = $$[$0];
case 16:this.$ = {}; this.$[$$[$0][0]] = $$[$0][1];
break;
case 11:this.$ = $$[$0];
case 17:this.$ = $$[$0-2]; $$[$0-2][$$[$0][0]] = $$[$0][1];
break;
case 12:this.$ = $$[$0];
case 18:this.$ = [];
break;
case 13:this.$ = $$[$0];
case 19:this.$ = $$[$0-1];
break;
case 14:this.$ = {};
case 20:this.$ = [$$[$0]];
break;
case 15:this.$ = $$[$0-1];
break;
case 16:this.$ = [$$[$0-2], $$[$0]];
break;
case 17:this.$ = {}; this.$[$$[$0][0]] = $$[$0][1];
break;
case 18:this.$ = $$[$0-2]; $$[$0-2][$$[$0][0]] = $$[$0][1];
break;
case 19:this.$ = [];
break;
case 20:this.$ = $$[$0-1];
break;
case 21:this.$ = [$$[$0]];
break;
case 22:this.$ = $$[$0-2]; $$[$0-2].push($$[$0]);
case 21:this.$ = $$[$0-2]; $$[$0-2].push($$[$0]);
break;
}
},
table: [{12:1,13:2,15:3,17:[1,4],23:[1,5]},{1:[3]},{14:[1,6]},{14:[1,7]},{3:11,4:[1,12],18:[1,8],19:9,20:10},{3:18,4:[1,12],5:19,6:[1,25],7:16,8:[1,22],9:17,10:[1,23],11:[1,24],13:20,15:21,16:15,17:[1,4],23:[1,5],24:[1,13],25:14},{1:[2,6]},{1:[2,7]},{14:[2,14],18:[2,14],22:[2,14],24:[2,14]},{18:[1,26],22:[1,27]},{18:[2,17],22:[2,17]},{21:[1,28]},{18:[2,1],21:[2,1],22:[2,1],24:[2,1]},{14:[2,19],18:[2,19],22:[2,19],24:[2,19]},{22:[1,30],24:[1,29]},{22:[2,21],24:[2,21]},{18:[2,8],22:[2,8],24:[2,8]},{18:[2,9],22:[2,9],24:[2,9]},{18:[2,10],22:[2,10],24:[2,10]},{18:[2,11],22:[2,11],24:[2,11]},{18:[2,12],22:[2,12],24:[2,12]},{18:[2,13],22:[2,13],24:[2,13]},{18:[2,3],22:[2,3],24:[2,3]},{18:[2,4],22:[2,4],24:[2,4]},{18:[2,5],22:[2,5],24:[2,5]},{18:[2,2],22:[2,2],24:[2,2]},{14:[2,15],18:[2,15],22:[2,15],24:[2,15]},{3:11,4:[1,12],20:31},{3:18,4:[1,12],5:19,6:[1,25],7:16,8:[1,22],9:17,10:[1,23],11:[1,24],13:20,15:21,16:32,17:[1,4],23:[1,5]},{14:[2,20],18:[2,20],22:[2,20],24:[2,20]},{3:18,4:[1,12],5:19,6:[1,25],7:16,8:[1,22],9:17,10:[1,23],11:[1,24],13:20,15:21,16:33,17:[1,4],23:[1,5]},{18:[2,18],22:[2,18]},{18:[2,16],22:[2,16]},{22:[2,22],24:[2,22]}],
defaultActions: {6:[2,6],7:[2,7]},
table: [{3:5,4:[1,12],5:6,6:[1,13],7:3,8:[1,9],9:4,10:[1,10],11:[1,11],12:1,13:2,15:7,16:8,17:[1,14],23:[1,15]},{1:[3]},{14:[1,16]},{14:[2,7],18:[2,7],22:[2,7],24:[2,7]},{14:[2,8],18:[2,8],22:[2,8],24:[2,8]},{14:[2,9],18:[2,9],22:[2,9],24:[2,9]},{14:[2,10],18:[2,10],22:[2,10],24:[2,10]},{14:[2,11],18:[2,11],22:[2,11],24:[2,11]},{14:[2,12],18:[2,12],22:[2,12],24:[2,12]},{14:[2,3],18:[2,3],22:[2,3],24:[2,3]},{14:[2,4],18:[2,4],22:[2,4],24:[2,4]},{14:[2,5],18:[2,5],22:[2,5],24:[2,5]},{14:[2,1],18:[2,1],21:[2,1],22:[2,1],24:[2,1]},{14:[2,2],18:[2,2],22:[2,2],24:[2,2]},{3:20,4:[1,12],18:[1,17],19:18,20:19},{3:5,4:[1,12],5:6,6:[1,13],7:3,8:[1,9],9:4,10:[1,10],11:[1,11],13:23,15:7,16:8,17:[1,14],23:[1,15],24:[1,21],25:22},{1:[2,6]},{14:[2,13],18:[2,13],22:[2,13],24:[2,13]},{18:[1,24],22:[1,25]},{18:[2,16],22:[2,16]},{21:[1,26]},{14:[2,18],18:[2,18],22:[2,18],24:[2,18]},{22:[1,28],24:[1,27]},{22:[2,20],24:[2,20]},{14:[2,14],18:[2,14],22:[2,14],24:[2,14]},{3:20,4:[1,12],20:29},{3:5,4:[1,12],5:6,6:[1,13],7:3,8:[1,9],9:4,10:[1,10],11:[1,11],13:30,15:7,16:8,17:[1,14],23:[1,15]},{14:[2,19],18:[2,19],22:[2,19],24:[2,19]},{3:5,4:[1,12],5:6,6:[1,13],7:3,8:[1,9],9:4,10:[1,10],11:[1,11],13:31,15:7,16:8,17:[1,14],23:[1,15]},{18:[2,17],22:[2,17]},{18:[2,15],22:[2,15]},{22:[2,21],24:[2,21]}],
defaultActions: {16:[2,6]},
parseError: function parseError(str, hash) {
throw new Error(str);
},
@@ -100,7 +94,7 @@ parse: function parse(input) {
token = self.symbols_[token] || token;
}
return token;
};
}
var symbol, preErrorSymbol, state, action, a, r, yyval={},p,len,newState, expected;
while (true) {
@@ -118,6 +112,7 @@ parse: function parse(input) {
}
// handle parse error
_handle_error:
if (typeof action === 'undefined' || !action.length || !action[0]) {
if (!recovering) {
@@ -128,7 +123,7 @@ parse: function parse(input) {
}
var errStr = '';
if (this.lexer.showPosition) {
errStr = 'Parse error on line '+(yylineno+1)+":\n"+this.lexer.showPosition()+'\nExpecting '+expected.join(', ');
errStr = 'Parse error on line '+(yylineno+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+expected.join(', ') + ", got '" + this.terminals_[symbol]+ "'";
} else {
errStr = 'Parse error on line '+(yylineno+1)+": Unexpected " +
(symbol == 1 /*EOF*/ ? "end of input" :
@@ -242,8 +237,10 @@ parse: function parse(input) {
}
return true;
}};/* Jison generated lexer */
var lexer = (function(){var lexer = ({EOF:1,
}};
/* Jison generated lexer */
var lexer = (function(){
var lexer = ({EOF:1,
parseError:function parseError(str, hash) {
if (this.yy.parseError) {
this.yy.parseError(str, hash);
@@ -279,6 +276,9 @@ more:function () {
this._more = true;
return this;
},
less:function (n) {
this._input = this.match.slice(n) + this._input;
},
pastInput:function () {
var past = this.matched.substr(0, this.matched.length - this.match.length);
return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, "");
@@ -303,6 +303,8 @@ next:function () {
var token,
match,
tempMatch,
index,
col,
lines;
if (!this._more) {
@@ -311,26 +313,31 @@ next:function () {
}
var rules = this._currentRules();
for (var i=0;i < rules.length; i++) {
match = this._input.match(this.rules[rules[i]]);
if (match) {
lines = match[0].match(/\n.*/g);
if (lines) this.yylineno += lines.length;
this.yylloc = {first_line: this.yylloc.last_line,
last_line: this.yylineno+1,
first_column: this.yylloc.last_column,
last_column: lines ? lines[lines.length-1].length-1 : this.yylloc.last_column + match[0].length}
this.yytext += match[0];
this.match += match[0];
this.matches = match;
this.yyleng = this.yytext.length;
this._more = false;
this._input = this._input.slice(match[0].length);
this.matched += match[0];
token = this.performAction.call(this, this.yy, this, rules[i],this.conditionStack[this.conditionStack.length-1]);
if (token) return token;
else return;
tempMatch = this._input.match(this.rules[rules[i]]);
if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
match = tempMatch;
index = i;
if (!this.options.flex) break;
}
}
if (match) {
lines = match[0].match(/\n.*/g);
if (lines) this.yylineno += lines.length;
this.yylloc = {first_line: this.yylloc.last_line,
last_line: this.yylineno+1,
first_column: this.yylloc.last_column,
last_column: lines ? lines[lines.length-1].length-1 : this.yylloc.last_column + match[0].length}
this.yytext += match[0];
this.match += match[0];
this.yyleng = this.yytext.length;
this._more = false;
this._input = this._input.slice(match[0].length);
this.matched += match[0];
token = this.performAction.call(this, this.yy, this, rules[index],this.conditionStack[this.conditionStack.length-1]);
if (this.done && this._input) this.done = false;
if (token) return token;
else return;
}
if (this._input === "") {
return this.EOF;
} else {
@@ -354,20 +361,27 @@ popState:function popState() {
},
_currentRules:function _currentRules() {
return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules;
},
topState:function () {
return this.conditionStack[this.conditionStack.length-2];
},
pushState:function begin(condition) {
this.begin(condition);
}});
lexer.options = {};
lexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) {
var YYSTATE=YY_START
switch($avoiding_name_collisions) {
case 0:/* skip whitespace */
break;
case 1:return 6;
case 1:return 6
break;
case 2:yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2); return 4;
case 2:yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2); return 4
break;
case 3: return 17
case 3:return 17
break;
case 4: return 18
case 4:return 18
break;
case 5:return 23
break;
@@ -389,8 +403,12 @@ case 13:return 'INVALID'
break;
}
};
lexer.rules = [/^\s+/,/^-?([0-9]|[1-9][0-9]+)(\.[0-9]+)?([eE][-+]?[0-9]+)?\b/,/^"(\\["bfnrt/\\]|\\u[a-fA-F0-9]{4}|[^\0-\x09\x0a-\x1f"\\])*"/,/^\{/,/^\}/,/^\[/,/^\]/,/^,/,/^:/,/^true\b/,/^false\b/,/^null\b/,/^$/,/^./];
lexer.conditions = {"INITIAL":{"rules":[0,1,2,3,4,5,6,7,8,9,10,11,12,13],"inclusive":true}};return lexer;})()
lexer.rules = [/^(?:\s+)/,/^(?:(-?([0-9]|[1-9][0-9]+))(\.[0-9]+)?([eE][-+]?[0-9]+)?\b)/,/^(?:"(?:\\[\\"bfnrt/]|\\u[a-fA-F0-9]{4}|[^\\\0-\x09\x0a-\x1f"])*")/,/^(?:\{)/,/^(?:\})/,/^(?:\[)/,/^(?:\])/,/^(?:,)/,/^(?::)/,/^(?:true\b)/,/^(?:false\b)/,/^(?:null\b)/,/^(?:$)/,/^(?:.)/];
lexer.conditions = {"INITIAL":{"rules":[0,1,2,3,4,5,6,7,8,9,10,11,12,13],"inclusive":true}};
;
return lexer;})()
parser.lexer = lexer;
return parser;
})();

View File

@@ -8,7 +8,7 @@
"lint",
"jsonlint"
],
"version": "1.0.1",
"version": "1.6.0",
"preferGlobal": true,
"repository": {
"type": "git",
@@ -22,9 +22,12 @@
"jsonlint": "lib/cli.js"
},
"engines": {
"node": "0.4 || 0.5"
"node": ">= 0.6"
},
"dependencies": {
"nomnom": ">= 1.5.x",
"JSV": ">= 4.0.x"
},
"dependencies": {},
"devDependencies": {
"test": "*",
"jison": "*",
@@ -33,5 +36,6 @@
"scripts": {
"test": "node test/all-tests.js"
},
"homepage": "http://zaach.github.com/jsonlint/"
}
"homepage": "http://zaach.github.com/jsonlint/",
"optionalDependencies": {}
}

View File

@@ -1,9 +1,8 @@
var fs = require('fs');
var sys = require('sys');
var source = "var jsonlint = (function(){var require=true,module=false;var exports={};" +
var source = "var jsonlint = (function(){var require=true,module=false;var exports={};" +
fs.readFileSync(__dirname+'/../lib/jsonlint.js', 'utf8') +
"return exports;})()";
sys.puts(source);
console.log(source);

View File

@@ -1,23 +1,24 @@
esc "\\"
int "-"?([0-9]|[1-9][0-9]+)
exp ([eE][-+]?[0-9]+)
frac ("."[0-9]+)
exp [eE][-+]?[0-9]+
frac "."[0-9]+
%%
\s+ {/* skip whitespace */}
{int}{frac}?{exp}?\b {return 'NUMBER';}
'"'("\\"["bfnrt/{esc}]|"\\u"[a-fA-F0-9]{4}|[^\0-\x09\x0a-\x1f"{esc}])*'"' {yytext = yytext.substr(1,yyleng-2); return 'STRING';}
"{" %{ return '{' %}
"}" %{ return '}' %}
"[" {return '['}
"]" {return ']'}
"," {return ','}
":" {return ':'}
"true" {return 'TRUE'}
"false" {return 'FALSE'}
"null" {return 'NULL'}
<<EOF>> {return 'EOF'}
. {return 'INVALID'}
\s+ /* skip whitespace */
{int}{frac}?{exp}?\b return 'NUMBER'
\"(?:'\\'[\\"bfnrt/]|'\\u'[a-fA-F0-9]{4}|[^\\\0-\x09\x0a-\x1f"])*\" yytext = yytext.substr(1,yyleng-2); return 'STRING'
"{" return '{'
"}" return '}'
"[" return '['
"]" return ']'
"," return ','
":" return ':'
"true" return 'TRUE'
"false" return 'FALSE'
"null" return 'NULL'
<<EOF>> return 'EOF'
. return 'INVALID'
%%

View File

@@ -1,20 +1,23 @@
%start JSONText
/*
/*
ECMA-262 5th Edition, 15.12.1 The JSON Grammar.
Modified to forbid top level primitives.
*/
/* author: Zach Carter */
%start JSONText
%%
JSONString
: STRING
{$$ = yytext;}
{ // replace escaped characters with actual character
$$ = yytext.replace(/\\(\\|")/g, "$"+"1")
.replace(/\\n/g,'\n')
.replace(/\\r/g,'\r')
.replace(/\\t/g,'\t')
.replace(/\\v/g,'\v')
.replace(/\\f/g,'\f')
.replace(/\\b/g,'\b');
}
;
JSONNumber
@@ -35,25 +38,17 @@ JSONBooleanLiteral
;
JSONText
: JSONObject EOF
{return $$ = $1;}
| JSONArray EOF
: JSONValue EOF
{return $$ = $1;}
;
JSONValue
: JSONNullLiteral
{$$ = $1;}
| JSONBooleanLiteral
{$$ = $1;}
| JSONString
{$$ = $1;}
| JSONNumber
{$$ = $1;}
| JSONObject
{$$ = $1;}
| JSONArray
{$$ = $1;}
;
JSONObject

View File

@@ -7,9 +7,25 @@ exports["test object"] = function () {
assert.deepEqual(parser.parse(json), {"foo": "bar"});
};
exports["test escaped backslash"] = function () {
var json = '{"foo": "\\\\"}';
assert.deepEqual(parser.parse(json), {"foo": "\\"});
};
exports["test escaped chars"] = function () {
var json = '{"foo": "\\\\\\\""}';
assert.deepEqual(parser.parse(json), {"foo": '\\\"'});
};
exports["test escaped \\n"] = function () {
var json = '{"foo": "\\\\\\n"}';
assert.deepEqual(parser.parse(json), {"foo": '\\\n'});
};
exports["test string with escaped line break"] = function () {
var json = '{"foo": "bar\\nbar"}';
assert.deepEqual(parser.parse(json), {"foo": "bar\\nbar"});
assert.deepEqual(parser.parse(json), {"foo": "bar\nbar"});
assert.equal(JSON.stringify(parser.parse(json)).length, 18);
};
exports["test string with line break"] = function () {
@@ -17,9 +33,24 @@ exports["test string with line break"] = function () {
assert["throws"](function () {parser.parse(json)}, "should throw error");
};
exports["test a json payload should be an object or array not a string"] = function () {
var json = fs.readFileSync(__dirname + "/fails/1.json").toString();
assert["throws"](function () {parser.parse(json)}, "should throw error");
exports["test string literal"] = function () {
var json = '"foo"';
assert.equal(parser.parse(json), "foo");
};
exports["test number literal"] = function () {
var json = '1234';
assert.equal(parser.parse(json), 1234);
};
exports["test null literal"] = function () {
var json = '1234';
assert.equal(parser.parse(json), 1234);
};
exports["test boolean literal"] = function () {
var json = 'true';
assert.equal(parser.parse(json), true);
};
exports["test unclosed array"] = function () {

View File

@@ -1 +0,0 @@
"A JSON payload should be an object or array, not a string."

File diff suppressed because one or more lines are too long