性能疯子 Blog

倚天照海花无数,流水山高心自知

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);
        }

 

posted @ 2016-02-26 15:53  性能疯子  阅读(30111)  评论(0编辑  收藏  举报
QQ联系我