How to capture elements in a json structure using javascript

Asked

Viewed 2,080 times

4

I need to get some elements inside a JSON structure with Javascript. 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 do a loop to capture ALL these "path" (SMALL) of ALL types of cards. I tried several ways but always return me error or Undefined.

I even followed the steps of this website which would be just 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
        }
    }
}
  • 1

    This json is poorly formed.

  • @Marcoantonioquintal, unfortunately it is like q esta in the manual of pagseguro :( ?

  • I do. I’ll do it here and I’ll send it to you. Just a few minutes.

  • have to pick up all small images including Boleto and Banco do Brasil? or just the dredit card?

  • CREDIT_CARD only

  • If you want I can pass the rest of the code you test in practice.

  • @A.A.F. to iterate all the cards this JSON needed to have an array for the cards and has no... Can you find the full JSON, at least with more than 1 card? As it is we will be guessing.

  • @Sergio, Nao sei se isso ajuda mas consigo pegar 2 "path" chamando diretamente: alert(response.paymentMethods.CREDIT_CARD.options.VISA.images.SMALL.path);
alert(response.paymentMethods.CREDIT_CARD.options.MASTERCARD.images.SMALL.path);

  • @A.A.F. Ok, in that case JSON lacks this information and you wouldn’t only know about JSON. Ok, I’ll put an answer for you to test.

  • @A.A.F: had given a problem in displaying my solution but now it’s ok. forehead there

  • @Marcoantonioquintal your solution is working p a card but when comes more than one of the error.

  • @A.A.F. It doesn’t work because the json that pagseguro put in is incomplete. you’re getting the webservice json? Look there. added another card and it worked. passes the full json of webservice.

  • @Marcoantonioquintal, you this Seminar. I tested and worked well. Now I only know how to accept two correct answers. Yours and Sergio’s.

  • Heats up no @A.A.F. Only helping is greater joy. Hug

Show 9 more comments

4 answers

5


If you can get these Alerts (as 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 that means that response.paymentMethods.CREDIT_CARD.options is an object with keys for each card. In this case you can 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
    };
});

This way you will have an array in the variable caminhos where each element of the array is an object with card type 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
});

3

I have made an attached . html file with what I think you want 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>
<div id="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>

1

I would like to leave a contribution too, I have 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);
  }
}

recalling that this method, is compatible with IE8 and lower versions , the function Object.Keys is not.

-1

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

 // 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);
                    }
                }
            }
        }
    }
}
  • Hello @hugomg, I wanted to go through all the JSON. Actually the q need is just the values that are in paymentMethods.CREDIT_CARD.options.NAMESAKE.images.SMALL.path path There are several cards (in NAMEPLATE).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.