An error occurs when attempting to access data from the JSON file

Currently, I am utilizing an API to retrieve the balance from a bitcoin address.

This is my code:

async function getWalletBalance(address) {
    try {
        const response = await got(`blockchain.info/balance?active=${address}`)
        return response.body.address.final_balance
    } catch(err) {
        return err
    }
}

The JSON that is being returned looks like this:

{
  "3D2oetdNuZUqQHPJmcMDDHYoqkyNVsFk9r": {
    "final_balance": 15392048444281,
    "n_tx": 3938,
    "total_received": 138450271881712
  }
}

However, when attempting to access the final balance, it returns undefined. What steps should I take to resolve this issue?

Answer №1

response.body.address.final_balance
is seeking the exact key address, not looking for the key
3D2oetdNuZUqQHPJmcMDDHYoqkyNVsFk9r
in your given example.

Using

response.body[address].final_balance
instead should resolve the issue.

The following code snippet has been slightly adjusted (without a real response) but is designed to work:

function getWalletBalance(address) {
    try {
        const body = {
          "3D2oetdNuZUqQHPJmcMDDHYoqkyNVsFk9r": {
            "final_balance": 15392048444281,
            "n_tx": 3938,
            "total_received": 138450271881712
          }
        };
        console.log('using body[address]:', body[address].final_balance);
    } catch(err) {
        return err
    }
}

getWalletBalance("3D2oetdNuZUqQHPJmcMDDHYoqkyNVsFk9r");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve JSON data for the initial request and showcase it on the homepage

After recently diving into Vue.js for the first time, I encountered a need to serialize Django objects. views.py def articles(request): model = News.objects.all() # obtaining a list of News objects modelSerialize = serializers.serial ...

The removeEventListener method seems to be malfunctioning when used within an if statement in my three.js code

I am relatively new to JavaScript, although I have a background in mathematics which includes concepts like coordinate systems and trigonometry. I've been learning JavaScript through Codecademy for the past couple of weeks, and recently attempted to c ...

Adjust the text color when you select an element

I am trying to figure out how to change the color of my "footertext" to red when I click on either the "left" or "center" containers. Then, I want it to go back to white when I click on any of the containers (left, right, center). This is my current HTML: ...

Ways to apply CSS styling to a specific SVG element without affecting others?

Originally, I had created a single bar chart using SVG: bars.append("rect") .attr("x", midX) .attr("y", 0) .attr("width", function(d) { return x(d.values[0].value); }) .attr("height", y.bandwidth()) .classed("highlight", function(d) { retu ...

Could not parse JSON after php file update. Everything was fine before switching to PDO, but now encountering a parsing issue

I encountered an issue where I could log in using a member from the database (MySQL) using Chrome, and create a new user successfully. However, when I tried to use the app, it crashed after attempting to create a new user. After testing some simple PHP co ...

transferring data using react-router

I'm working on a code that displays four images, and when one of them is clicked, it should take up the entire screen. I am using React Router to implement this functionality. Here's the current code setup: App.js import React from 'react&a ...

Switch the background image of a link within an accordion with a simple click

I'm attempting to create a toggle effect for a background image on a links within an FAQ accordion using javascript. After referencing this jsfiddle example (http://jsfiddle.net/QwELf/), I was able to get things to function. You can view my page in ...

Content changing programmatically does not reset the scrollHeight

As I embark on the journey to expand my coding skills, I have decided to challenge myself by tackling some tasks without relying on jQuery. One particular challenge that I am currently facing involves a fixed contenteditable div. The goal is to adjust the ...

Dealing with large integers in JSON when inserting them into a MongoDB database can be a complex task

Challenge : I am dealing with a highly intricate json file that contains integer values exceeding 8 Bytes (c_time, p_time), along with some smaller ones like id in the example below. Sample structure: { "c_time": 18446744062065078000 ...

Updating React Native using setState is not possible

In my React Native application, there is a function that deletes an item: delete(index){ this.setState({deletedIndex:index, cachedCart:this.state.Cart, Cart: this.state.Cart.splice(index,1) }, function(){ console.log(th ...

Connecting JavaScript and jQuery scripts

Help needed! I am a beginner in the world of jQuery and JS. Unfortunately, my JS/jQuery code is not running and I can't figure out why. Can someone please take a look at my HTML and guide me on what might be causing the issue? Do I need to add some ad ...

Persist the checkbox value in the database and update the status of the label accordingly

I need a checkbox for user preference selection that is stored in a MySQL database for constant availability. The label should change to "Enabled" when the checkbox is selected and vice versa. Upon saving (submitting) the page, an alert message should disp ...

The jQuery Multiselect filter contradicts the functionality of single select feature

http://jsfiddle.net/rH2K6/ <-- The Single Select feature is functioning correctly in this example. $("select").multiselect({ multiple: false, click: function(event, ui){ } http://jsfiddle.net/d3CLM/ <-- The Single Select breaks down in this sc ...

Is there a way to prevent javascript from automatically inserting tags when selecting text?

If you want to view the Fiddle Here Essentially, it's a text-highlighting tool that works almost flawlessly. The problem arises when it encounters tags like <p> or <br> within the selection. The JavaScript code seems to automatically in ...

When clicking initially, the default input value in an Angular 2 form does not get set

I am currently learning angular2 as a beginner programmer. My goal is to create a form where, upon clicking on an employee, an editable form will appear with the employee's current data. However, I have encountered an issue where clicking on a user f ...

Utilizing ajax and json, information is transmitted between two PHP files before being returned back

Attempting to transfer data from file No1 to file No2 using ajax and JSON, then back from file No2 to file No1 Below is the code in file No1: HTML <div id="first_var">1 one</div> <div id="second_var">2 two</div> <div id="load" ...

Address properties that are undefined before they cause an error

Is there a smart way to manage undefined properties and/or identifiers on an object before they result in failure/returning undefined? Can we intercept access to a non-defined property and address it without resorting to try/catch blocks? var myObj = { ...

Refreshing Bootstrap table data after an AJAX post request

I have implemented a bootstrap table to display rows from a database in MVC ASP.NET. The data is stored in a ViewBag and then returned with the ViewBag included as data to be displayed. Here is an example of how it looks: <div class="row rpad"> ...

Deciphering JSON data within Azure functions using C#

I am dealing with receiving a Json that contains multiple lines in Azure, and the format is not consistent. The number of lines and variables I receive can vary greatly, with up to 20 variables possible. {"Data":[ {"name":"Variable A","value":0.321721,"ti ...

Tips for incorporating AngularJS with dynamically added elements

Essentially, I have a structure similar to this example The formula for every cell in the last column should be: value[i][2] = value[i-1][2] + value[i][0] - value[i][1] I'm currently facing two issues. The first one arises when attempting to progra ...