0

How to check in an JSON object, the input path is present or not?

var obj = {
  "schemaOne": {
    "name": "abc",
    "Path": "i.abc",
    "count": 5347,
    "subFolders": [

    ]
  },
  "schemaTwo": {
    "name": "cde",
    "Path": "i.cde",
    "count": 0,
    "subFolders": [
      {
        "name": "efg",
        "Path": "",
        "count": 0,
        "subFolders": [

        ]
      },
      {
        "name": "hij",
        "Path": "i.hij",
        "count": 1,
        "subFolders": [

        ]
      }
    ]
  }
}

var inputpath = "obj.count";

After doing several research I came across below code. Here in this code, o.Path is known to the user. But I want to modify the code so tat dynamically check obj.count is present in JSON object or not?

function upd(o, path, count) {
  if (o.Path == path) {
    o.count = count;
  } else {
    var arr;
    if (Array.isArray(o)) arr = o;
    else if (o.subFolders) arr = o.subFolders;
    else return;
    for(var j=0; j < arr.length; j++) {
      upd(arr[j], path, count);
    }
  }
}
Biffen
  • 6,249
  • 6
  • 28
  • 36
user87267867
  • 1,409
  • 3
  • 18
  • 25

1 Answers1

0

Your question isn't very clear, neither the use case. As someone told u, obj is a JavaScript object, not a JSON.

If I understood correctly, you want to check if a path, espressed as string (such as "obj.count") exists in that object.

A very fast but not safe solution (eval is evil and should be avoided almost in every case) could be:

if(eval(inputpath)){
    //... do something
}

In alternative, I suggest you to write a function that gets an object and a string (path) as parameter, parses the string path and check if the object contains such path.

Start from here: Accessing nested JavaScript objects with string key

Community
  • 1
  • 1
Lorenzo Marcon
  • 8,029
  • 5
  • 38
  • 63
  • I tried the code but for array index which is unknown it is throwing undefined [ http://jsfiddle.net/user87267867/uLL0a9u0/ ] – user87267867 Sep 11 '14 at 11:22
  • well, if the index it's unknown, that's not a valid path, and you can't use it. In your example, try `schemaTwo.subFolders[0].name` instead – Lorenzo Marcon Sep 11 '14 at 12:12