如何在可能是简单字符串或字符串对象的字符串对象上安全地使用 JSON.parse? [英] How can I safely use JSON.parse on a string object that might be a simple string or a string object?
本文介绍了如何在可能是简单字符串或字符串对象的字符串对象上安全地使用 JSON.parse?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要能够解析对象格式或纯字符串格式的字符串.最安全的方法是什么?
I need to be able to parse a string in an object format or in a plain string format. what is the safest way to do this?
我尝试了 JSON.parse(data) 但它在数据是纯字符串的情况下不起作用.
I tried JSON.parse(data) but it does not work in case that data is a plain string.
谢谢你,这就是我解决问题的方法:
Thanks to you, this is how I solved the problem:
try {
dataObj = JSON.parse(data);
} catch (err) {
if (typeof data === "object") {
dataObj = data;
} else {
dataObj = {};
}
}
推荐答案
使用 try catch:
Use try catch:
var result;
try {
result = JSON.parse(data);
} catch (err) {
if (typeof data == 'string') result = data;
else console.error(err);
}
这篇关于如何在可能是简单字符串或字符串对象的字符串对象上安全地使用 JSON.parse?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文