Home > OS >  typescript - load json from url and get access to array of json objects
typescript - load json from url and get access to array of json objects

Time:07-29

I just can't find a working solution and implement in my format.

There is a JSON file which is returned to me by URL. Its format is:

{"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"
    }]

}

Due to the fact that it is returned via the URL, it is not possible to directly use the object, for example:

myobj['data']['price']

I have either a string of data that I can convert using JSON.parse() or an object right away. But for some reason I can't use it directly.

As far as I understand, this is a JSON file inside which is an array of JSON data. My goal is to display all the data from the array, while taking for example 2 values: price, quantity

How can I access the values that I want to get?

CodePudding user response:

   var data = JSON.parse(response.data);
   console.log(data[1].price);

output:

46

CodePudding user response:

Ok I find, what I was looking for. I return result not in json, but in text response.text()

After I did this, I create a new constant called res and put in it JSON.parse(data)

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

const res = JSON.parse(data)

After all this manipulations I can use my data with 2 ways:

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

Or I can make a cocktail from it, by using my favorite blender :)))

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