Skip to content

Commit

Permalink
Merge 2045a90 into a13eb6e
Browse files Browse the repository at this point in the history
  • Loading branch information
alsotang committed Aug 21, 2015
2 parents a13eb6e + 2045a90 commit 7756384
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
18 changes: 15 additions & 3 deletions lib/json.js
Expand Up @@ -10,10 +10,22 @@
* Module dependencies.
*/

function throwNotObject() {
throw new Error('JSON string is not object');
}

exports.strictJSONParse = function (str) {
var obj = JSON.parse(str);
if (!obj || typeof obj !== 'object') {
throw new Error('JSON string is not object');
if (str === '') {
return throwNotObject();
}

str = str.trim();

if (str[0] !== '{') {
return throwNotObject();
}

var obj = JSON.parse(str);

return obj;
};
7 changes: 7 additions & 0 deletions test/json.test.js
Expand Up @@ -22,6 +22,13 @@ describe('json.test.js', function () {
obj.should.eql({foo: 'bar'});
});


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

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

0 comments on commit 7756384

Please sign in to comment.