javascript - Handling exception from unparsable input into JSON.parse() -
javascript - Handling exception from unparsable input into JSON.parse() -
i came across issue while creating way manage cookies in js. cookies can contain strings in json format:
var cookiecontents = '{"type":"cookie","islie":true}'; ... or plain strings:
var cookiecontents = 'the cookie lie'; to parse cookie, ideally json.parse(cookiecontents). problem json.parse() cannot parse plain string , throws fatal error.
my question what best/most accepted way handle situation this?
i have tried using try/catch statement:
var cookie1 = '{"type":"cookie","islie":true}'; var cookie2 = 'the cookie lie'; function parsecookiestring(str){ var output; try{ output = json.parse(str); } catch(e){ output = str; } console.log(output); } parsecookiestring(cookie1); // outputs object parsecookiestring(cookie2); // outputs string http://jsfiddle.net/fmpeyton/7w60cesp/
this works fine, feels dirty. maybe because not handle js fatal errors. is mutual handle fatal errors more gracefully in scenario this?
doing seek grab makes sense if json.parse throws error because of else output variable end containing did not intend.
that's interesting problem though. - checking presence of { , } in string:
function parsecookiestring(str){ var output; if (!!str.match(/^{.+}$/)) { output = json.parse(str); } else { output = str; } console.log(output); } parsecookiestring(cookie1); // outputs object parsecookiestring(cookie2); // outputs string javascript json parsing
Comments
Post a Comment