I'm not sure my JSON is formatted correctly to access it

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) notifies the JSON structure for debugging purposes.

How to access the breed section of a JSON object and all of the following indexes / keys?

+4
source share
6 answers

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" } } ] 

You have an array [] two objects {} .

First you need a for (var i = 0; i < JSON.length; i++) loop for (var i = 0; i < JSON.length; i++) to get each object (of which you have 2).

Excerpt:

 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); } } 
+1
source

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

actually How do I skip or list a JavaScript object?

+2
source

Use console.info in FireFox and you can render the object.

+1
source

The easiest way to ensure json is correct is to increment the array in php that you need and then use http://php.net/manual/en/function.json-encode.php in the array for you send it back

+1
source

Here is the JSFiddle Demo:

For example, if this is your output JSON object, you can access the index of each breed using the 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 will remove two objects under each of the two breeds.

+1
source

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); } 
0
source

All Articles