Skip to content

Instantly share code, notes, and snippets.

@gucheen
Created August 25, 2015 05:51
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gucheen/12b90451f04733078d7f to your computer and use it in GitHub Desktop.
Save gucheen/12b90451f04733078d7f to your computer and use it in GitHub Desktop.
Safe JSON.parse with lodash.js
function parseLodash(str){
return _.attempt(JSON.parse.bind(null, str));
}
@Ben52
Copy link

Ben52 commented Mar 22, 2016

Nice. You can use this to validate JSON:

function isValidJson(str) {
   return _.isError(parseLodash(str));
}

@bllevy
Copy link

bllevy commented Jul 19, 2017

I know this is an old gist, but could you explain why you used _.attempt(JSON.parse.bind(null, str)) instead of just _.attempt(JSON.parse, str)?

I've seen the _.attempt(JSON.parse.bind(null, str)) used elsewhere, but no explanation has been provided.

@RubenMateus
Copy link

ok

@itsDiwaker
Copy link

@bllevy so that this is hard bound to our preference and left at the mercy of _.attempt or a foreign function. I think it's just a protective pattern.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment