[英]Parse string to json with string mixed
I want to parse a string var to json object, however it is not json all the time. 我想将字符串var解析为json对象,但是并非始终都是json。 If it is not json I want it to be returned as it. 如果不是json,我希望将其返回。 I tried JSON.parse, but it will post error when the var is pure string, finally I got JSON.parse(JSON.stringify(var)), I wonder whether there is a way to judge a string can be parse to json or not, so I can save the "stingify" phase. 我尝试了JSON.parse,但是当var是纯字符串时它将发布错误,最后我得到了JSON.parse(JSON.stringify(var)),我想知道是否有一种判断字符串的方法可以解析为json还是否,因此我可以保存“精简”阶段。
you can use try / catch. 您可以使用try / catch。 if you get exception when you try to parse it, it means that it is not valid json 如果在尝试解析它时遇到异常,则意味着它不是有效的json
var victim=....;
var output;
try {
output = JSON.parse(victim);
} catch (e) {
output = victim;
}
There's no better way than actually parsing and knowing if its valid or not. 没有比实际解析和知道其是否有效更好的方法了。 You can use try
/ catch
blocks to set the variable and then return it. 您可以使用try
/ catch
块来设置变量,然后返回它。
function toJSON(str) {
var rtn;
try { rtn = JSON.parse(str); } // try to set it
catch (e) { rtn = str; } // if error set it to str
return rtn; // finally return
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.