javascript - 使用 jQuery 检查 JSON 对象中是否存在键

我已经完成了 AJAX 验证,验证后的消息以 JSON 数组的形式返回。因此,我需要检查诸如 nameemail 之类的键是否在该 JSON 数组中。

{
    "name": {
        "isEmpty": "Value is required and can't be empty"
    },
    "email": {
        "isEmpty": "Value is required and can't be empty"
    }
}

仅当键名存在时,我才需要将错误消息写入 name 字段。

以下是输入字段时显示错误的代码

if (obj['name']'isEmpty'] != "") {                                 
   $('#name').after(c1 + "<label class='error'>" + obj['name']['isEmpty'] + "</label>");
}                                       
if (obj['email']['isEmpty'] != "" ) { 
   $('#email').after(c4 + "<label class='error'>" + obj['email']['isEmpty'] + "</label>");
}

但如果输入了name字段,则不会出现在JSON数组中。 所以检查语句

if (obj['name']['isEmpty'] != "")

会导致以下错误:

obj.name not found


数组中不必有键 name。同时,如果数组拥有键 name,我需要检查是否显示错误。

最佳答案

使用 JavaScript 的 hasOwnProperty()功能:

if (json_object.hasOwnProperty('name')) {
    //do necessary stuff
}

https://stackoverflow.com/questions/8893020/

相关文章:

ajax - 为什么 jqXHR.responseText 返回字符串而不是 JSON 对象?

java - 如何将 JSON 字段名称映射到不同的对象字段名称?

javascript - 如何在 JSON 中存储 javascript 函数

django - 使用 django 测试客户端发送 JSON

java - 如何在 Eclipse 中导入 javax.json

json - 如何将 JSON 文件导入 TypeScript 文件?

javascript - Ajax调用完成后执行函数

java - Gson 将一组数据对象转换为 json - Android

json - Newtonsoft 对象 → 获取 JSON 字符串

json - 如何将 Django 查询集输出为 JSON?