Noobie Nooberson
Noobie Nooberson

Reputation: 67

How can I count fields in a JSON based on their content

I'm new to JS an this is likely a noob question, but I can't seem to find an answer which I figure may be due to my lack of correct terminology.

Basically I'm trying to count how many "active" fields in a JSON file are set to true vs false and return those values to a variable. I'm just getting lost trying to figure out how to go about this.

For example, my JSON is named data and looks like this:

{
"systems": [
    {
        "name": "SV001",
        "IP": "10.1.1.101",
        "active": "true"
    },
    {
        "name": "SV002",
        "IP": "10.1.1.102",
        "active": "true"
    },
    {
        "name": "SV003",
        "IP": "10.1.1.103",
        "active": "false"
    }
]}

Any help would be greatly appreciated.

Upvotes: 1

Views: 2873

Answers (1)

Pratik Pambhar
Pratik Pambhar

Reputation: 184

You could parse into the json object from string like var json=JSON.parse(jsonString); And than by looping you can get the value.

var count=0;
for(var i=0i<json.systems.length;i++){
  if(json.systems[i].active){
    count++;
  }
}

you can have count at the end of loop.

Upvotes: 1

Related Questions