diff --git a/lib/util/js.js b/lib/util/js.js index 05c9562..9366510 100644 --- a/lib/util/js.js +++ b/lib/util/js.js @@ -28,11 +28,16 @@ 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) { return false; } + if (typeof(parsed) === 'object') { + return true; + } + return false; }, isHexa: isHexa, isHexaString: isHexa, diff --git a/test/privatekey.js b/test/privatekey.js index 7cae44b..dcaab92 100644 --- a/test/privatekey.js +++ b/test/privatekey.js @@ -16,6 +16,7 @@ var invalidbase58 = require('./data/bitcoind/base58_keys_invalid.json'); describe('PrivateKey', function() { var hex = '96c132224121b509b7d0a16245e957d9192609c5637c6228311287b1be21627a'; + var hex2 = '8080808080808080808080808080808080808080808080808080808080808080'; var buf = new Buffer(hex, 'hex'); var wifTestnet = 'cSdkPxkAjA4HDr5VHgsebAPDEh9Gyub4HK8UJr2DFGGqKKy4K5sG'; var wifTestnetUncompressed = '92jJzK4tbURm1C7udQXxeCBvXHoHJstDXRxAMouPG1k1XUaXdsu'; @@ -31,6 +32,12 @@ describe('PrivateKey', function() { should.exist(b.bn); }); + it('should create a privatekey from hexa string', function() { + var a = new PrivateKey(hex2); + should.exist(a); + should.exist(a.bn); + }); + it('should create a new random testnet private key with only one argument', function() { var a = new PrivateKey(Networks.testnet); should.exist(a); diff --git a/test/util/js.js b/test/util/js.js new file mode 100644 index 0000000..b392300 --- /dev/null +++ b/test/util/js.js @@ -0,0 +1,35 @@ +'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"]}'; + var json2 = '["value", "value2", {"key": "value"}]'; + + 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); + }); + + it('correctly validates an array json object', function() { + var valid = JSUtil.isValidJSON(json); + valid.should.equal(true); + }); + + }); + +});