How to capture elements in a json structure using javascript

4

I need to get some elements inside a Javascript JSON framework. I can get unit elements like this:

alert(response.paymentMethods.CREDIT_CARD.options.MASTERCARD.images.SMALL.path);
alert(response.paymentMethods.CREDIT_CARD.options.VISA.images.SMALL.path);

But I need to make a loop to capture ALL of these "SMALL" paths of ALL card types. I have tried in many ways but they always return me error or undefined .

I've even followed the steps from this site that would be exactly what I need, but without success.

Javascript :

PagSeguroDirectPayment.getPaymentMethods({
    success: function(response) {
        //meios de pagamento disponíveis 
    },
    error: function(response) {
        //tratamento do erro 
    },
    complete: function(response) {
        //tratamento comum para todas chamadas 
    }
});

JSON :

{
    "error":false,
    "paymentMethods":{
        "BOLETO":{
            "name":"BOLETO",
            "options":{
                "BOLETO":{
                    "name":"BOLETO",
                    "displayName":"Boleto",
                    "status":"AVAILABLE",
                    "code":202,
                    "images":{
                        "SMALL":{
                            "size":"SMALL",
                            "path":"/public/img/payment-methods-flags/42x20/booklet.png"
                        },
                        "MEDIUM":{
                            "size":"MEDIUM",
                            "path":"/public/img/payment-methods-flags/68x30/booklet.png"
                        }
                    }
                }
            },
            "code":2
        },
        "ONLINE_DEBIT":{
            "name":"ONLINE_DEBIT",
            "options":{
                "BANCO_BRASIL":{
                    "name":"BANCO_BRASIL",
                    "displayName":"Banco do Brasil",
                    "status":"AVAILABLE",
                    "code":304,
                    "images":{
                        "SMALL":{
                            "size":"SMALL",
                            "path":"/public/img/payment-methods-flags/42x20/bb.png"
                        },
                        "MEDIUM":{
                            "size":"MEDIUM",
                            "path":"/public/img/payment-methods-flags/68x30/bb.png"
                        }
                    }
                },

            },
            "code":3
        },
        "CREDIT_CARD":{
            "name":"CREDIT_CARD",
            "options":{
                "MASTERCARD":{
                    "name":"MASTERCARD",
                    "displayName":"MasterCard",
                    "status":"AVAILABLE",
                    "code":102,
                    "images":{
                        "SMALL":{
                            "size":"SMALL",
                            "path":"/public/img/payment-methods-flags/42x20/mastercard.png"
                        },
                        "MEDIUM":{
                            "size":"MEDIUM",
                            "path":"/public/img/payment-methods-flags/68x30/mastercard.png"
                        }
                    }
                },

            },
            "code":1
        }
    }
}
    
asked by anonymous 04.01.2015 / 18:54

4 answers

5

If you can get these alerts ( as you indicated in the comments ):

alert(response.paymentMethods.CREDIT_CARD.options.VISA.images.SMALL.path);
alert(response.paymentMethods.CREDIT_CARD.options.MASTERCARD.images.SMALL.path);

So it means that response.paymentMethods.CREDIT_CARD.options is an object with keys for each card. In this case it is possible to iterate like this:

var cartoes = response.paymentMethods.CREDIT_CARD.options;
var caminhos = Object.keys(cartoes).map(function(cartao){
    return {
        tipo: cartao,
        path: cartoes[cartao].images.SMALL.path
    };
});

In this way you will have an array in the variable caminhos where each element of the array is an object with type of the card and path.

If you just want to iterate the cards you can use:

Object.keys(cartoes).forEach(function(cartao){
    var path = cartoes[cartao].images.SMALL.path;
    // fazer algo com path
});
    
04.01.2015 / 22:43
3

I made an .html file attached to what I think you're trying to do. Please check if this is it. Follow the html code below. Just copy, save as html and test in your browser.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><divid="bandeiras">

</div>
<script>
    var jsonText = '{ ' +
                '"error":false, ' +
                '"paymentMethods":{ ' +
                '"BOLETO":{ ' +
                '"name":"BOLETO", ' +
                '"options":{ ' +
                '"BOLETO":{ ' +
                '"name":"BOLETO", ' +
                '"displayName":"Boleto", ' +
                '"status":"AVAILABLE", ' +
                '"code":202, ' +
                '"images":{ ' +
                '"SMALL":{ ' +
                '"size":"SMALL", ' +
                '"path":"/public/img/payment-methods-flags/42x20/booklet.png" ' +
                '}, ' +
                '"MEDIUM":{ ' +
                '"size":"MEDIUM", ' +
                '"path":"/public/img/payment-methods-flags/68x30/booklet.png" ' +
                '} ' +
                '} ' +
                '} ' +
                '}, ' +
                '"code":2 ' +
                '}, ' +
                '"ONLINE_DEBIT":{ ' +
                '"name":"ONLINE_DEBIT", ' +
                '"options":{ ' +
                '"BANCO_BRASIL":{ ' +
                '"name":"BANCO_BRASIL", ' +
                '"displayName":"Banco do Brasil", ' +
                '"status":"AVAILABLE", ' +
                '"code":304, ' +
                '"images":{ ' +
                '"SMALL":{ ' +
                '"size":"SMALL", ' +
                '"path":"/public/img/payment-methods-flags/42x20/bb.png" ' +
                '}, ' +
                '"MEDIUM":{ ' +
                '"size":"MEDIUM", ' +
                '"path":"/public/img/payment-methods-flags/68x30/bb.png" ' +
                '} ' +
                '} ' +
                '} ' +
                '}, ' +
                '"code":3 ' +
                '}, ' +
                '"CREDIT_CARD":{ ' +
                '"name":"CREDIT_CARD", ' +
                '"options":{ ' +
                '"MASTERCARD":{ ' +
                '"name":"MASTERCARD", ' +
                '"displayName":"MasterCard", ' +
                '"status":"AVAILABLE", ' +
                '"code":102, ' +
                '"images":{ ' +
                '"SMALL":{ ' +
                '"size":"SMALL", ' +
                '"path":"/public/img/payment-methods-flags/42x20/mastercard.png" ' +
                '}, ' +
                '"MEDIUM":{ ' +
                '"size":"MEDIUM", ' +
                '"path":"/public/img/payment-methods-flags/68x30/mastercard.png" ' +
                '} ' +
                '} ' +
                '}, ' +
                '"VISA":{ ' +
                '"name":"VISA", ' +
                '"displayName":"MasterCard", ' +
                '"status":"AVAILABLE", ' +
                '"code":102, ' +
                '"images":{ ' +
                '"SMALL":{ ' +
                '"size":"SMALL", ' +
                '"path":"/public/img/payment-methods-flags/42x20/visa.png" ' +
                '}, ' +
                '"MEDIUM":{ ' +
                '"size":"MEDIUM", ' +
                '"path":"/public/img/payment-methods-flags/68x30/visa.png" ' +
                '} ' +
                '} ' +
                '} ' +
                '}, ' +
                '"code":1 ' +
                '} ' +
                '} ' +
                '}';
    var jsonObj = JSON.parse(jsonText);
    $("#bandeiras").append('<h1>bandeiras</h1>');
    $.each(jsonObj.paymentMethods.CREDIT_CARD.options, function (index, value) {
        console.log(this.images.SMALL.path);
        $("#bandeiras").append('<img src="https://stc.pagseguro.uol.com.br'+this.images.SMALL.path+'">');
    });
</script>
    
04.01.2015 / 22:36
1

I would like to leave a contribution too, I already used this api, my solution was like this,

var cartoes = response.paymentMethods.CREDIT_CARD.options;
var i;
for(i in cartoes){
  if(cartoes.hasOwnProperty(i)){
      console.log(cartoes[i].images.SMALL.path);
  }
}

This method is compatible with IE8 and lower versions, since the Object.keys function is not.

    
24.01.2017 / 17:11
-1

If I understand correctly, your problem is in the "CREDIT_CARD", "MASTERCARD" and "SMALL" sections, right? If so, what you need is to use the for-in loop to traverse the keys of an object

 // Esse código imprime "a", "b" e "c", não necessariamente nessa ordem
 var obj = {a:1, b:2, c:3}
 for(var k in obj){
     if(Object.prototype.hasOwnProperty.apply(obj, k){
         console.log(k);
     }
 }

In your case:

var payment = response.paymentMethods;
for(var ptype in payment){
    if(Object.prototype.hasOwnProperty.call(payment, ptype)){
        var options = payment[ptype].options;
        for(var otype in options){
            if(Object.prototype.hasOwnProperty.call(options, otype)){
                var images = options[otype].images;
                for(var size in images){
                    if(Object.prototype.hasOwnProperty.call(images, size)){
                        var path = images[size].path;
                        console.log(path);
                    }
                }
            }
        }
    }
}
    
04.01.2015 / 20:22