/**
* Determine if a string is JSON
* @param {String} string A string to test
* @return {Boolean|Object} If it is JSON, it will be parsed, otherwise it returns false
*/
export default function isJson(string) {
try {
const parsed = JSON.parse(string);
// Eliminate the funny things JSON.parse is willing to handle that isn't JSON
if (parsed && typeof parsed === 'object') {
return parsed;
}
// Go gentle into that good night
} catch (e) {} // eslint-disable-line no-empty
return false;
}
import isJson from '../isJson';
describe('isJson', () => {
it('should detect if a string is JSON by parsing it', () => {
const json = JSON.stringify({
mock: 'Rick',
number: 1
});
const isJsonTest = isJson(json);
expect(isJsonTest)
.toMatchObject({
mock: 'Rick',
number: 1
});
});
it('should properly handle a null type by returning false', () => {
// JSON.stringify can be passed null successfully
// This test should return false
const isJsonTest = isJson(null);
expect(isJsonTest)
.toBeFalsy();
});
it('should properly handle a number type by returning false', () => {
// JSON.stringify can be passed undefined successfully
// This test should return false
const isJsonTest = isJson(100);
expect(isJsonTest)
.toBeFalsy();
});
it('should properly handle a boolean type by returning false', () => {
// JSON.stringify can be passed a boolean successfully
// This test should return false
const isJsonTest = isJson(true);
expect(isJsonTest)
.toBeFalsy();
});
it('should properly handle a string type by returning false', () => {
// JSON.stringify can be passed a string successfully
// This test should return false
const isJsonTest = isJson('Rick and Morty');
expect(isJsonTest)
.toBeFalsy();
});
});