In TypeScript, fetch JSON data from a URL and gain access to an array of JSON objects

I'm struggling to find a solution and implement it in the correct format.

An API returns a JSON file to me via a URL. The format is as follows:

{"success":true,

    "data":[
    {
      "loadTimestamp":"2022-07-20T15:12:35.097Z",
      "seqNum":"9480969",
      "price":"45.7",
      "quantity":"0.2",
      "makerClientOrderId":"1658329838469",
      "takerClientOrderId":"1658329934701"
    },
    {
      "loadTimestamp":"2022-07-20T14:49:11.446Z",
      "seqNum":"9480410",
      "price":"46",
      "quantity":"0.1",
      "makerClientOrderId":"1658328403394",
      "takerClientOrderId":"0"
    }]

}

Since it is received via URL, I cannot directly access the object using code like:

myobj['data']['price']

I have the option to either convert the data from a string using JSON.parse(), or work with it as an object. However, I am facing difficulties in using it directly.

It seems like the JSON file contains an array of data inside it. My objective is to display all the data from the array, focusing on values like price and quantity.

How can I extract the specific values I need?

Answer №1

Finally, I have located what I was searching for. Instead of receiving the outcome in JSON format, I am now extracting it from the text using response.text()

Upon accomplishing this task, I established a new constant named res and stored JSON.parse(data) within it

const website  = 'https://myurl.com/'+pub_key
const feedback = await fetch(website)
let data = ''
if (feedback.ok) { data = await feedback.text() } else { console.log("Error HTTP: " + feedback.status) }

const res = JSON.parse(data)

Following these steps, I can access my data in two different manners:

console.log(res["data"][0]["price"])
console.log(res.data[0].price)

Alternatively, I could mix it up and create a delicious cocktail using my trusty blender :)))

if(res.success==true){
    for(let element in res.data){
        console.log(res.data[element].price,res.data[element].quantity)
    }
}

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

A Guide on Using Multiple Clauses to Filter Data in Elasticsearch

I'm working on filtering a data set based on two conditions. The goal is to retrieve records that satisfy either condition 1 (containing A and B) or condition 2 (containing A and C), with wildcards included. For instance, consider the following table ...

What are the steps to incorporate JSON into my ActionScript 3 code?

Looking for assistance with my Flash game coded in AS3. It sends variables score and game_id using my customized encryption class called CryptoCode. I aim to send these variables (score and game_id) as an encrypted JSON object to PHP. Any suggestions on h ...

Python tutorial: Efficiently sorting dictionaries by their values

I have a collection of dictionaries that I want to filter and generate a vector corresponding to their values. Each dictionary in the list contains data like time, item, state: {values1, value2, value3}. The variable item can assume 11 different values ran ...

The API for monitoring Jenkins build time trends through curl does not produce any results

I received a link to access the Build Time Trend and other data in Jenkins. https://jenkins:8080/view/<view-name>/job/<job-name>/<buildnumber>/api/json The link functions properly when used in a web browser, however, it does not work wi ...

Clicking on an icon to initiate rotation (Material UI)

Is there a way to toggle the rotation of an icon (IconButton) based on the visibility of a Collapse component? I want it to point down when the Collapse is hidden and up when it's shown. const [expanded, setExpanded] = useState<boolean>(false); ...

What is the best way to track events in angular-meteor when a user logs in, logs out, or when there is a change in the user

I am working on meteor-angular and trying to track new user login and logout changes within a single component. I have attempted to subscribe to userData in the component's initialization, but it does not seem to detect when the user logs in or out. I ...

Verify if the value is larger or smaller in WireMock

I am currently in a scenario where I must verify the amount and generate an appropriate response based on its value. If the amount is greater than or equal to 100, then a specific response should be returned. For amounts less than 100, an error response n ...

Rediscovering the Depths of Nested JSON Arrays in Postgres

I've been diligently searching for a solution to this specific issue, but unfortunately, I haven't come across anything that aligns closely with what I'm seeking. Within my database, I have two distinct tables: CREATE TABLE skill_tree ( ...

Issue with Value Update in Angular 7 Reactive Forms

I am encountering an issue where the data in my formgroup does not update upon submission. The formgroup successfully retrieves values from an API, but when attempting to update and return the value, it remains unchanged. I am unsure of what mistake I may ...

Pinia is having trouble importing the named export 'computed' from a non-ECMAScript module. Only the default export is accessible in this case

Having trouble using Pinia in Nuxt 2.15.8 and Vue 2.7.10 with Typescript. I've tried numerous methods and installed various dependencies, but nothing seems to work. After exhausting all options, I even had to restart my main folders on GitHub. The dep ...

Having trouble transforming the JSON object into a usable format

Although I'm still getting the hang of JSON, please bear with me if this seems like a rookie mistake. My approach involves sending a query to a local file that performs a cURL operation on an external site's API and returns a JSON object. Due to ...

Retrieve information from the accuweather api endpoint

I am struggling to retrieve JSON data from the AccuWeather API using a locationKey in PHP. The error message I am receiving is: file_get_contents(https://dataservice.accuweather.com/forecasts/v1/daily/1day/55488?apikey=0NSY9T1tFGo0NIXOYp23lro8DsuOcwPJ): fa ...

Tips for effectively transmitting JSON data through SuperAgent within the React framework

Currently, I am transmitting the state of my react app to a server that is not located on the same server as the frontend. request.post('http://localhost:8000/guide') .send(JSON.stringify(this.state)) .end((err, resp) =&g ...

Using Node to upload various large JSON files into mongoDB

Currently, I am dealing with the task of parsing numerous large JSON files into my mongoDB database. To accomplish this, I have been utilizing the stream-json npm package. The process involves loading one file at a time, then manually changing the filename ...

Encountering a Runtime Exception while setting up a Client Component in the latest version of Next JS (v13.3

I am facing an issue with a component in my Next JS website. When I attempt to convert it into a Client Component, the page fails to load in the browser and I encounter the following unhandled runtime exception: SyntaxError: "undefined" is not va ...

Arranging JSON structure using json_build_object and json_build_array functions within Postgresql

I'm attempting to replicate this JSON structure using json_build_object and json_build_array functions in PostgreSQL Here is the desired output: [ { "name": "Albert", "Gender": "Male", "tags": [ "Student", "Geography" ] ...

Increasing the PHP memory limit while updating large JSON files can help improve performance and

I am facing an issue with my shared hosting provider regarding the 128Mb memory limit. The problem arises when I try to integrate data from AJAX into a PHP controller, which then accesses a file, parses the new data from AJAX, and updates that file by addi ...

Angular 2/4 throws an Error when a Promise is rejected

I implemented an asynchronous validator function as shown below. static shouldBeUnique(control: AbstractControl): Promise<ValidationErrors | null> { return new Promise((resolve, reject) => { setTimeout(() => { if (contr ...

The AJAX request encountered an error due to an Unexpected End of JSON Input

My AJAX code is encountering an error message. parsererror (index):75 SyntaxError: Unexpected end of JSON input at parse (<anonymous>) at Nb (jquery.min.js:4) at A (jquery.min.js:4) at XMLHttpRequest.<anonymous> (jquery.min.js: ...

Using Json with React's Context API

I am dealing with nested JSON and arrays within it. My goal is to create a Search functionality that will iterate through the arrays and, based on a specific ID, display the name of the corresponding object in the array. I attempted using the Context API ...