Skip to content

Commit

Permalink
Merge pull request #5 from tewen/tewen/is-json-string
Browse files Browse the repository at this point in the history
Added the isJsonString method to the json module.
  • Loading branch information
tewen committed Jun 10, 2019
2 parents 19b465f + a625218 commit 1670c5d
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 2 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,17 @@ flattenObject(obj);
```


#### isJsonString(str)

Returns a boolean that specifies whether the string is parsable JSON.

```JavaScript
const str = JSON.stringify({red: 5, green: 6});

isJsonString(str); // true
```


#### stringToBoolean(str)

Usually used for url parameters, converts null, undefined, 0, false, or '' to false even if they are strings. All other values are true.
Expand Down
9 changes: 9 additions & 0 deletions lib/json.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
const _ = require('lodash');

function isJsonString(str) {
try {
return _.isObject(JSON.parse(str));
} catch (e) {
return false;
}
}

function safeJsonParse(obj) {
if (obj && _.isString(obj)) {
try {
Expand All @@ -12,5 +20,6 @@ function safeJsonParse(obj) {
}

module.exports = {
isJsonString,
safeJsonParse
};
38 changes: 36 additions & 2 deletions test/json.spec.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,42 @@
const { expect } = require('chai');

const { safeJsonParse } = require('../');
const { isJsonString, safeJsonParse } = require('../');

describe('json', function () {
describe('isJsonString()', function () {
it('should return false if passed undefined', function () {
expect(isJsonString(undefined)).to.be.false;
});

it('should return false if passed null', function () {
expect(isJsonString(null)).to.be.false;
});

it('should return false if passed a blank string', function () {
expect(isJsonString('')).to.be.false;
});

it('should return false if passed a number', function () {
expect(isJsonString(555)).to.be.false;
});

it('should return false if passed an invalid json object string', function () {
expect(isJsonString('{"red":5,"green":55,"blue":Koolaid"}')).to.be.false;
});

it('should return false if passed an invalid json array string', function () {
expect(isJsonString('["Red","Green","Blue"')).to.be.false;
});

it('should return true if passed a valid json object string', function () {
expect(isJsonString('{"red":5,"green":55,"blue":"Koolaid"}')).to.be.true;
});

it('should return true if passed a valid json array string', function () {
expect(isJsonString('["Red","Green","Blue"]')).to.be.true;
});
});

describe('json', function() {
describe('safeJsonParse()', function () {
it('should return null if passed undefined', function () {
expect(safeJsonParse(undefined)).to.be.null;
Expand Down

0 comments on commit 1670c5d

Please sign in to comment.