JS中判断JSON数据是否存在某字段的方法 JavaScript中判断json中是否有某个字段

方式一 !("key" in obj) 
方式二 obj.hasOwnProperty("key")  //obj为json对象。

实例:

        var jsonworld_pose = JSON.parse(data[0].world_pose);
        var jsonorientation = jsonworld_pose.orientation; //次处可能为undefined
        var jsonposition = jsonworld_pose.position;//次处可能为undefined

        if (jsonworld_pose.hasOwnProperty("orientation")) {//使用时先进行判断
            $("#orientation-w").html(jsonorientation.w);
            $("#orientation-x").html(jsonorientation.x);
            $("#orientation-y").html(jsonorientation.y);
            $("#orientation-z").html(jsonorientation.z);
        }

        if (jsonworld_pose.hasOwnProperty("position")) {
            $("#position-x").html(jsonposition.x);
            $("#position-y").html(jsonposition.y);
            $("#position-z").html(jsonposition.z);
        }
原文地址:https://www.cnblogs.com/cdemo/p/5220685.html