4

Here is another JSON question (I always struggle with arrays).

My PHP code returns the following JSON structure:

[{"breed":{"msg":"Breed is required","placement":"#breed_error_1","return":"false"}},{"breed":{"msg":"Breed does not exist","placement":"#breed_error_2","return":"true"}}] 

My PHP code is:

$breed[]["breed"] = array("msg"=>"Breed is required","placement"=>"#breed_error_1", "return"=>"false");
$breed[]["breed"] = array("msg"=>"Breed does not exist","placement"=>"#breed_error_2", "return"=>"true");  

And the AJAX code:

$.ajax({
    type: 'POST',
    cache: false,
    url: "validate_breed",
    data: element+"="+$(elementSelector).val()+"&v="+validateElement,
    context: document.body,
    dataType: 'html',
    success: function(data){
        alert(data);

    }
});

alert(data) alerts out the JSON structure for debugging purposes.

How do I access the breed section of JSON object and all of the following index/keys?

Oscar Mederos
  • 29,016
  • 22
  • 84
  • 124
dottedquad
  • 1,371
  • 6
  • 24
  • 55

6 Answers6

2

A for(item in data) loop should do the trick, there are other articles around that talk about getting the values

actually How do I loop through or enumerate a JavaScript object?

Community
  • 1
  • 1
Ascherer
  • 8,223
  • 3
  • 42
  • 60
1

Use console.info in FireFox and you'll be able to visualize the object.

Omar Abid
  • 15,753
  • 28
  • 77
  • 108
1

Here is the JSON reformatted:

[
   {
      "breed":{
         "msg":"Breed is required",
         "placement":"#breed_error_1",
         "return":"false"
      }
   },
   {
      "breed":{
         "msg":"Breed does not exist",
         "placement":"#breed_error_2",
         "return":"true"
      }
   }
]

What you have is an array [] of two objects {}.

To start with you'd do a for (var i = 0; i < JSON.length; i++) loop to get each object (of which you have 2).

Snippet:

for (var i = 0, len = JSON.length; i < len; i++){
    thisBreed = JSON[i].breed; //now this == {"msg" : etc etc}
    for (prop in thisBreed) {
        console.log(thisBreed.msg + thisBreed.placement + thisBreed.return);
    }
}
Alex Mcp
  • 19,037
  • 12
  • 60
  • 93
  • In order for me to get this to work successfully I needed to do: var myObject = eval('(' + data + ')'); Apparently I needed to use eval for all examples given by everyone answering my question. The data type is set to JSON so, Why is eval still required? -Rich – dottedquad May 12 '11 at 02:57
  • 1
    Because what comes over the wire is still just a string of text. It might happen to look like JSON or XML or whatever, but until some sort of parser goes through it (like eval() for javascript) it won't mean anything. Sorry to have left this out. jQuery ajax can be set to do it automagically, fwiw. – Alex Mcp May 12 '11 at 03:27
  • No worries Alex. I fully understand this now :-) – dottedquad May 12 '11 at 04:23
  • @dottedquad on the php side before you echo out the output to ajax, did you `json_encode` your output array? – KJYe.Name May 12 '11 at 12:50
  • Yes I did. My encode code is: $this->breed_return = json_encode($breed); – dottedquad May 13 '11 at 04:24
1

The simplest way ensure proper json is to bulid the array in php tw way you want it then use http://php.net/manual/en/function.json-encode.php on the array befor you send it back

mcgrailm
  • 17,469
  • 22
  • 83
  • 129
  • `function breed_check($str) { $breed = array(); if($str == NULL) { $breed[0]["breed"] = array("msg"=>"Breed is required","placement"=>"#breed_error_1", "return"=>"false"); $breed[1]["breed"] = array("msg"=>"Breed does not exist","placement"=>"#breed_error_2", "return"=>"true"); } $this->breed_return = json_encode($breed); }` I did form the array then did json_encode. Code snippet is included – dottedquad May 12 '11 at 01:51
1

Here is the JSFiddle Demo:

For instance if this is your output JSON object, then you can access index of each breed using a for loop:

var myJSON = [{
    "breed": {
        "msg": "Breed is required",
        "placement": "#breed_error_1",
        "return": "false"
    }},
{
    "breed": {
        "msg": "Breed does not exist",
        "placement": "#breed_error_2",
        "return": "true"
    }}];

for(var i=0;i<myJSON.length; i++){
     console.log(myJSON[i].breed);
}

This would console output two objects under each of the two breed

KJYe.Name
  • 16,969
  • 5
  • 48
  • 63
  • I created a new .js file and .html file to test out your example. I understand how this works now; however, when I implement this example into my project I receive the following error in firebug: myJSON[i].breed is undefined http://pastebin.com/KhG6K7V9 – dottedquad May 12 '11 at 01:57
  • @dottedquad can you post what `console.log(myJSON)` gives you? – KJYe.Name May 12 '11 at 02:18
  • The code works when I implemented var myObject = eval('(' + data + ')'); As Alex Mcp explained, "Until some sort of parser goes through it (like eval() for javascript) it won't mean anything." – dottedquad May 13 '11 at 04:27
0

Try This one

for (var i = 0, len = JSON.length; i < len; i++){
  console.log(JSON[i].breed.msg +" - "+ JSON[i].breed.placement +" - "+ JSON[i].breed.return);
}
GDP
  • 8,109
  • 6
  • 45
  • 82
Lalit Bhudiya
  • 4,332
  • 4
  • 26
  • 32