【发布时间】:2014-10-27 23:09:39
【问题描述】:
我在创建一种在 JS 中管理 cookie 的方法时遇到了这个问题。我的 cookie 可以包含 JSON 格式的字符串:
var cookieContents = '{"type":"cookie","isLie":true}';
...或者只是简单的字符串:
var cookieContents = 'The cookie is a lie';
要解析 cookie,我最好使用JSON.parse(cookieContents)。这样做的问题是JSON.parse() 无法解析纯字符串并引发致命错误。
我的问题是处理这种情况的最佳/最广泛接受的方法是什么?
我尝试过使用 try/catch 语句:
var cookie1 = '{"type":"cookie","isLie":true}';
var cookie2 = 'The cookie is a 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/
这很好用,但感觉很脏。也许是因为我通常不处理 JS 致命错误。 在这种情况下更优雅地处理致命错误是否很常见?
【问题讨论】:
-
这实际上是
JSON.parse()中的设计错误(哦!JavaScript 中的设计错误!如此罕见!哦等等...)-> 这不是致命错误,它应该返回 @ 987654328@ 什么的。或者它应该有一个只检查有效性的方法(比如JSON.isValid(),这可能是最干净的解决方案。)
标签: javascript json parsing