Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

reading json in javascript from a get request

good day, i have been trying the read data from my json output sent from a flask json dump via javascript.

$.ajax({
type: "GET",
url: m_url+"bank_trans/get_banks/",
credentials: 'include', 
headers: {
    'AccessToken': acc,
},
success:function(data) {
  console.log(data)

  for (i=0; i<data.length; i++){
     console.log(
         data.total_amount + "<br />"
     );
  }


}

});

The output of the json dump, from console.log

[{"total_amount": 1254275355.95, "BANK_NAME": "FIRST BANK"}, {"total_amount": 49307548.55, "BANK_NAME": "GT BANK"}, {"total_amount": 100000.00, "BANK_NAME": "STANBIC IBTC BANK"}, {"total_amount": 79100000.00, "BANK_NAME": "STERLING BANK"}, {"total_amount": 50133150.68, "BANK_NAME": "UBA"}, {"total_amount": 13000000.00, "BANK_NAME": "ZENITH BANK"}]

thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For now data is a JSON content : a string, you need to load it as a JS structure, here a list of objects

Simple solution

Parse the JSON, and also use data[i].total_amount and not data.total_amount

let data = '[{"total_amount": 1254275355.95, "BANK_NAME": "FIRST BANK"}, {"total_amount": 49307548.55, "BANK_NAME": "GT BANK"}, {"total_amount": 100000.00, "BANK_NAME": "STANBIC IBTC BANK"}, {"total_amount": 79100000.00, "BANK_NAME": "STERLING BANK"}, {"total_amount": 50133150.68, "BANK_NAME": "UBA"}, {"total_amount": 13000000.00, "BANK_NAME": "ZENITH BANK"}]'
data = JSON.parse(data)
for (i=0; i<data.length; i++){
    console.log(data[i].total_amount);
}

Better solution

Regarding jquery.ajax

Use dataType: "json" to load automatically from JSON

$.ajax({
    type: "GET",
    dataType: "json",
    url: m_url + "bank_trans/get_banks/",
    credentials: 'include',
    headers: {
        'AccessToken': acc,
    },
    success: function(data) {
        console.log(data)
        for (i=0; i < data.length; i++){
            console.log(data[i].total_amount);
        }
    }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading