Skip to content

Instantly share code, notes, and snippets.

@nemisj
Last active November 28, 2016 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nemisj/4b2902e2e7fedc57a6896dfbd35da3ca to your computer and use it in GitHub Desktop.
Save nemisj/4b2902e2e7fedc57a6896dfbd35da3ca to your computer and use it in GitHub Desktop.
'use strict';
const parse = require('json-safe-parse');
module.exports = (str) => {
let json = str;
if (typeof str === 'string') {
const toParse = str.trim();
if (toParse !== '') {
json = parse(toParse, 'throw');
} else {
return {};
}
}
if (/^(undefined|null)$/.test(json)) {
return {};
} else if (typeof json === 'object') {
return json;
}
// it's some value
throw new Error('It is not an object');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment