javascript - Handling exception from unparsable input into JSON.parse() -


I came to the issue while creating a way to manage cookies in JS. String in my cookies that can be in JSON format:

  var cookieContents = '{"type": "cookie", "islie": true}';  

... or are just plain strings:

  var cookieContents = 'cookie is a lie';  

To parse the cookie, I would like to do the ideal JSON.parse . The problem with this JSON.parse () can not parse a plain string and throws a serious error.

My question is What is the best / most accepted way

I have tried to try / catch:

  var cookie1 '' {"type": "cookie", "isLie": true} '; Var cookie2 = 'Cookie is a lie'; Function parseCookieString (str) {var output; Try {output = JSON.parse (str); } Hold (e) {output = str; } Console.log (output); } ParseCookieString (cookie1); // Output Object Parse Cookies String (Cookie 2); // output string  

This works perfectly well, but looks dirty probably because I usually do not control JS malignant errors Is it very common to handle fatal errors in such a scenario?

It is understandable by holding a try, but if JSON.parse < / Code> causes an error due to something other than your output variable, then it can end the thing you do not intend. / P>

This is an interesting problem, though. I will do something like - checking the presence in the string of originally { {/ code> and } :

  function parseCookieString (Str) {Var output; If (!! str.match (/ ^ {. +} $ /)) {Output = JSON Prs (str); } Else {output = str; } Console.log (output); } ParseCookieString (cookie1); // Output Object Parse Cookies String (Cookie 2); // output string  

Comments