0

Inside the json object I traverse upto 4 level something any of the level may undefined and code break.

How validate/check json node in JavaScript not in jquery

productDetail.breadcrumb.levels.push(paramObj.categories.category.category.category.CATEGORYNAME);
Elankeeran
  • 6,134
  • 9
  • 40
  • 57

2 Answers2

1

You need to check it like this :

var categoryName = (paramObj.categories 
                    && paramObj.categories.category
                    && paramObj.categories.category.category
                    && paramObj.categories.category.category.CATEGORYNAME);

This will give you the category name or undefined if any of the objects along the way are not there.

Woody
  • 7,578
  • 2
  • 21
  • 25
0

Abstract it out into a checking function

function myJsonValue(ob, prop) {
    var propsArray = prop.split('.');
    var out = ob;
    var i;
    for (i=0; i < propsArray.length; i += 1){
        var dis = propsArray[i];
        if (!out[dis]) {
            return undefined;
        }
        out = out[dis];

    }
    return out;
}

Usage:

myJsonValue(paramObj, "categories.category.category.category.CATEGORYNAME")

(Fiddle)

chim
  • 8,407
  • 3
  • 52
  • 60
  • For in is meant for iterating over object property lists. See http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript – Woody Jan 15 '14 at 16:17