0

The below script returns 2 Alerts (F3 and S1). I would need 4 alerts (F1, F2, F3 and S1) - that's the host names of all the services.

I guess that the each function is creating an Array that does not contain doublets - so it's only giving me one - the last one F3.

How can I get the host_names of all the services ? I can not change the input data.

SCRIPT:

 <script>
    $(function () {
        var status = [];
        $.ajaxSetup({
            cache: false
        });
        $.getJSON('status.php', function (data) {
            $.each(data.services, function (i, f) {
                alert(f.host_name);
            });
        });
    });
</script>

OUPUT from status.php:

{
"hosts": {
   "modified_host": "0",
   "modified_serv": "0"
},
"services": {
  "HTTPS": {
      "host_name": "F1",
      "service_description": "HTTPS"
  },
  "HTTPS": {
      "host_name": "F2",
      "service_description": "HTTPS"
  },
  "HTTPS": {
      "host_name": "F3",
      "service_description": "HTTPS"
  },
  "HTTP": {
      "host_name": "S1",
      "service_description": "HTTP"
  }
}
}
Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265
  • Services should be stored as an array. Stored like in your code you will end up with only 2 services of them with key `HTTPS` (the last one declared only) and `HTTP` – GillesC Jul 25 '14 at 11:59
  • I think it can help you : http://stackoverflow.com/questions/5306741/do-json-keys-need-to-be-unique – Isabek Tashiev Jul 25 '14 at 12:02

1 Answers1

0

You can't have multiple identical indexes in the same level of a JSON String. E.g : try to JSONLint your string and you will get :

{
    "hosts": {
        "modified_host": "0",
        "modified_serv": "0"
    },
    "services": {
        "HTTPS": {
            "host_name": "F3",
            "service_description": "HTTPS"
        },
        "HTTP": {
            "host_name": "S1",
            "service_description": "HTTP"
        }
    }
}

That's what JSON.parse() — called (I guess) by $.getJSON — , returns.

Your status.php needs to return an array for 'services' :

  "services": [{
      "host_name"          : "F1",
      "service_description": "HTTPS"
    }, {
      "host_name"          : "F2",
      "service_description": "HTTPS"
    }, {
      "host_name"          : "F3",
      "service_description": "HTTPS"
    }, {
      "host_name"          : "S1",
      "service_description": "HTTP"
    }
  ]
meriadec
  • 2,953
  • 18
  • 20
  • 1
    i thought exactly the same, but as the author said: he can not change the input data (output of status.php)... – Merlin Denker Jul 25 '14 at 12:08
  • Thank's you for the answers. Doesn't look to good I guess. Is there no way to manipulate the data while calling the getJson function? Like adding a counter to the all the service names, to make them end up as unique names in the array ? – user3876709 Jul 28 '14 at 14:05