/ / Accès aux objets JSON stringifiés - javascript, jquery, json

Accès aux objets JSON stringifiés - javascript, jquery, json

En tant qu'autre utilisateur dans mon autre fil a suggéré de poster une autre question ici concernant l'explication de l'accès aux objets JSON. Le code que j'utilise est:

<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$.getJSON(
"https://api.guildwars2.com/v1/wvw/matches.json",
function (data) {
$("#reply").html(JSON.stringify(data));
// or work with the data here, already in object format
});
});
</script>

Ce que j'essaie de faire avec le code JSON, consiste à rechercher world_id et retourner le match_id. Je suis très nouveau sur JavaScript, donc je ne sais pas trop comment le faire et comment accéder aux données stringifiées que le code ci-dessus me donne.

La façon dont j'ai compris comment procéder est de créer un tableau et d'y stocker chaque objet, puis de parcourir et de vérifier un identifiant correspondant,

if(obj[i].red_world_id == "xxxx" || obj[i].blue_world_id == "xxxx" || obj[i].green_world_id == "xxxx") {
return obj[i].wvw_match_id;
}

Mon seul problème est que je ne sais pas comment définir un tableau en tant que données JSON.

Réponses:

2 pour la réponse № 1

.utiliser ce code -

$(function() {
$.getJSON("https://api.guildwars2.com/v1/wvw/matches.json", function(
data) {
$("#reply").html(JSON.stringify(data));
// or work with the data here, already in object format
var result = [];//for if it has many matches
for ( var i=0;i<data.wvw_matches.length;i++ ) {
var obj = data.wvw_matches[i];
if (obj.red_world_id == "xxxx" || obj.blue_world_id == "xxxx"
|| obj.green_world_id == "xxxx") {
result.push(obj.wvw_match_id);
}
}
});
});

1 pour la réponse № 2

Il n'est pas nécessaire de stringifier, vous pouvez travailler directement avec l'objet JSON:

function(data) {
var filteredArray=$.grep(data.wvw_matches, function (item) {
return (item.red_world_id == "xxxx" || item.blue_world_id == "xxxx" || item.green_world_id == "xxxx");
});
}

Voir cette page pour plus d'informations sur jQuery.grep.