From c20a0eabed129a13039040af1997aca384e33177 Mon Sep 17 00:00:00 2001 From: Braydon Fuller Date: Fri, 2 Jan 2015 19:32:49 -0500 Subject: [PATCH] Check type of parsed JSON to determine it's an object and not a number. --- lib/util/js.js | 8 +++++++- test/privatekey.js | 2 +- test/util/js.js | 29 +++++++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 test/util/js.js diff --git a/lib/util/js.js b/lib/util/js.js index 85c1284..3316062 100644 --- a/lib/util/js.js +++ b/lib/util/js.js @@ -28,9 +28,15 @@ module.exports = { * @return {Object|boolean} false if the argument is not a JSON string. */ isValidJSON: function isValidJSON(arg) { + var parsed; try { - return JSON.parse(arg); + parsed = JSON.parse(arg); } catch (e) { + parsed = false; + } + if (typeof(parsed) === 'object') { + return true; + } else { return false; } }, diff --git a/test/privatekey.js b/test/privatekey.js index 3212bd4..dcaab92 100644 --- a/test/privatekey.js +++ b/test/privatekey.js @@ -32,7 +32,7 @@ describe('PrivateKey', function() { should.exist(b.bn); }); - it('should create a privatkey from hexa string', function() { + it('should create a privatekey from hexa string', function() { var a = new PrivateKey(hex2); should.exist(a); should.exist(a.bn); diff --git a/test/util/js.js b/test/util/js.js new file mode 100644 index 0000000..197ccdf --- /dev/null +++ b/test/util/js.js @@ -0,0 +1,29 @@ +'use strict'; +/* jshint unused: false */ + +var should = require('chai').should(); +var expect = require('chai').expect; + +var bitcore = require('../..'); +var JSUtil = bitcore.util.js; + +describe('js utils', function() { + + describe('isValidJSON', function() { + + var hexa = '8080808080808080808080808080808080808080808080808080808080808080'; + var json = '{"key": ["value", "value2"]}'; + + it('does not mistake an integer as valid json object', function() { + var valid = JSUtil.isValidJSON(hexa); + valid.should.equal(false); + }); + + it('correctly validates a json object', function() { + var valid = JSUtil.isValidJSON(json); + valid.should.equal(true); + }); + + }); + +});