Javascript中的JSON对象验证 [英] JSON Object validation in Javascript

查看:85
本文介绍了Javascript中的JSON对象验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using JSON object as an input in the textfield. Is there any way to validate this JSON object in javascript??

推荐答案

基于@Quentin的想法,你可以做到类似于:

Building on the idea of @Quentin, you can just do something like:

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

console.log(isValidJson("{}")); // true
console.log(isValidJson("abc")); // false

这将需要 json2.js ,以确保对 JSON 的跨浏览器支持对象

This will require json2.js to be deployed in the page in order to ensure cross-browser support for the JSON Object.

这篇关于Javascript中的JSON对象验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆