Skip to content

Commit

Permalink
Merge pull request node-modules#12 from node-modules/strict-json
Browse files Browse the repository at this point in the history
feat(JSON): add strict JSON parse
  • Loading branch information
fengmk2 committed May 22, 2015
2 parents 8fb20d0 + aa7700a commit c58862a
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 0 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,13 @@ var res = utils.try(function () {
// {error: Error, value: undefined}
```

### JSON

```
var obj = utils.strictJSONparse('"hello"');
// will throw when JSON string is not object
```

## benchmark

* [jsperf: access log date format](http://jsperf.com/access-log-date-format)
Expand Down
19 changes: 19 additions & 0 deletions lib/json.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*!
* utility - lib/crypto.js
*
* MIT Licensed
*/

"use strict";

/**
* Module dependencies.
*/

exports.strictJSONParse = function (str) {
var obj = JSON.parse(str);
if (!obj || typeof obj !== 'object') {
throw new Error('JSON string is not object');
}
return obj;
};
1 change: 1 addition & 0 deletions lib/utility.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ copy(require('./function'))
.and(require('./number'))
.and(require('./string'))
.and(require('./array'))
.and(require('./json'))
.and(require('./date'))
.and(require('./map'))
.and(require('./web'))
Expand Down
43 changes: 43 additions & 0 deletions test/json.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**!
* utility - test/json.test.js
*
* MIT Licensed
*
* Authors:
* fengmk2 <[email protected]> (http://fengmk2.github.com)
*/

'use strict';

/**
* Module dependencies.
*/

var utils = require('../');

describe('json.test.js', function () {
describe('strictJSONParse()', function () {
it('should parse normal json ok', function () {
var obj = utils.strictJSONParse('{"foo": "bar"}');
obj.should.eql({foo: 'bar'});
});

it('should parse error when invalid json', function () {
(function () {
utils.strictJSONParse('{');
}).should.throw();
});

it('should parse error when non-object json', function () {
(function () {
utils.strictJSONParse('"hello"');
}).should.throw();
});

it('should parse error when null json', function () {
(function () {
utils.strictJSONParse('null');
}).should.throw();
});
});
});

0 comments on commit c58862a

Please sign in to comment.