Last active
November 28, 2016 11:31
-
-
Save nemisj/4b2902e2e7fedc57a6896dfbd35da3ca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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