Javascript中的JSON对象验证

use*_*229 7 javascript validation json

我在文本字段中使用JSON对象作为输入.有没有办法在javascript中验证这个JSON对象?

jab*_*lab 19

基于@Quentin的想法,您可以执行以下操作:

function isValidJson(json) {
    try {
        JSON.parse(json);
        return true;
    } catch (e) {
        return false;
    }
}

console.log(isValidJson("{}")); // true
console.log(isValidJson("abc")); // false
Run Code Online (Sandbox Code Playgroud)

这将需要在页面中部署json2.js以确保跨浏览器支持JSON Object.