0
{
    "data": [{
        "niccode": 12,
        "dangerousprocess": 1,
        "numofworkers": 32,
        "avgworkers": 8,
        "numoffactory": 1,
        "row_no": 1
    }, {
        "niccode": 18,
        "dangerousprocess": 2,
        "numofworkers": "",
        "avgworkers": 9,
        "numoffactory": 1,
        "row_no": 2
    }, {
        "niccode": 28,
        "dangerousprocess": 2,
        "numofworkers": 40,
        "avgworkers": 110,
        "numoffactory": 1,
        "row_no": 3
    }]
}

This is my JSON array. How can I count niccode? (count of niccode=3). Please help.

5
  • what? do you have any question? Commented Mar 9, 2015 at 11:09
  • what's wrong with data.length ? Commented Mar 9, 2015 at 11:14
  • data.length doesn't be worked. Commented Mar 9, 2015 at 11:16
  • 1
    You need obj.data.length where obj is the variable referring to this object Commented Mar 9, 2015 at 11:17
  • 1
    If you have always a niccode property inside a data objects, then with a data.length is enough Commented Mar 9, 2015 at 11:33

2 Answers 2

2

Try this:

     $(document).ready(function() {
        var jsonData= {"data":[{"niccode":12,"dangerousprocess":1,"numofworkers":32,"avgworkers":8,"numoffactory":1,"row_no":1},{"niccode":18,"dangerousprocess":2,"numofworkers":"","avgworkers":9,"numoffactory":1,"row_no":2},{"niccode":28,"dangerousprocess":2,"numofworkers":40,"avgworkers":110,"numoffactory":1,"row_no":3}]};

            var Niccode = countJsonKey(jsonData, 'niccode');
            alert(Niccode);
        });



 function countJsonKey(jsonData, countThis){
            var i = 0;
            $.each(jsonData.data, function(key, obj) {
                if(typeof(obj[countThis]) != 'undefined'){
                    i++;
                }
            });
            return i;
        }
Sign up to request clarification or add additional context in comments.

Comments

1

You can try

  // obj is your json
  var obj = {"data":[{"niccode":12,"dangerousprocess":1,"numofworkers...
  var count = obj.data.filter(function (e) {return e.niccode !== undefined;}).length;

Hope it works

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.