简体   繁体   中英

Check json data for value and then get its key

I have some JSON data that I am retrieving from https://status.mojang.com/check and am storing in a variable. I'm still quite new to JSON/JS and I can't seem to find any answers on google.

Code:

function checkMojang() {
 var mojangStatus = mojang.status();
 mojangStatus.then(function (message) {
     var response = JSON.parse(message);
 })
}

Data I am using can be seen at the link above. I am trying to check all the data in the json array, see if any of the values contain "yellow" or "red" and get the keys for those values along with their checked value but can't figure out how to do so.

you can use the method array.foreach() to execute a provided function once per array element and the for ... in to itarate over the enumarable properties. So you can test the value and get keys for the value "yellow" or "red"

response.forEach(function(element) {
    for (k in element) {
        if (element[k]=="red" or element[k]=="yellow") {
            // k is the key
        }
    }
});

You can loop through the array and then through the object properties and make a new object using the colors as keys

 var response = [{"minecraft.net":"green"},{"session.minecraft.net":"red"},{"account.mojang.com":"green"},{"auth.mojang.com":"green"},{"skins.minecraft.net":"green"},{"authserver.mojang.com":"yellow"},{"sessionserver.mojang.com":"green"},{"api.mojang.com":"green"},{"textures.minecraft.net":"green"},{"mojang.com":"red"}]; var new_response = {}; response.forEach(function(obj){ for (var prop in obj) { if(obj.hasOwnProperty(prop)) { if(new_response[obj[prop]] == undefined) new_response[obj[prop]] = []; new_response[obj[prop]].push(prop); } } }) console.log(new_response); 

The you can use the object for your needs as

new_response["red"]

giving you the list of all key with red value.

function checkMojang() {
    var mojangStatus = mojang.status();
    mojangStatus.then(function (message) {
        var response = JSON.parse(message);

        for (i = 0; i < response.length; i++) { // iterate over response array
            var item = response[i];             // get item from array
            var key = Object.keys(item)[0];     // get the key of the item
            var value = item[key];              // get the value of the item

            if (value === 'yellow' || value === 'red') {
                // do something, like adding it to a list
            }
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM