1

Good day Developers in the house. I need help. I have a json string that i have gotten from API in Angular and console log to see it. I want to get a particular data from the json file and store in a variable because i need to query the data again. Below is how my Json data look like.

{
  "done": true,
  "record_id": "5fc0a7ac88d2f8534f8e59d8",
  "customer_id": "5fa1541f6bd09b290f736608",
  "balance": {
    "clientId": "qh8RKp9BGhmKCn8ZAAED",
    "status": true,
    "balance_callback": "https://webhook.site/92b09e29-f08e-4472-b7e8-5875155360d67",
    "data": {
      "formatted": [
        {
          "available_balance": 31500,
          "ledger_balance": 32000,
          "ref": "saving-account",
          "status": "active",
          "account": "5fa9e536f6b7bb837cb22byu",
          "connected": true
        },
        {
          "available_balance": 11200,
          "ledger_balance": 11200,
          "ref": "current-account",
          "status": "active",
          "account": "5fa9e535f6b7bb837cb22buy",
          "connected": false
        },
        {
          "available_balance": 2000,
          "ledger_balance": 2000,
          "ref": "current-account",
          "status": "active",
          "account": "5fa9e536f6b7bb837cb22bty",
          "connected": false
        }
      ]
    }
  },
  "Post": {
    "callback_url": "https://webhook.site/92b09e29-f08e-4472-b7e8-5875155360d67"
  },
  "guarantors": [],
  "redirect_url": "",
  "launchAgain": true,
  "hideExit": "",
  "options": {},
  "directors": null,
  "auth": {
    "clientId": "qh8RKp9BGhmKCn8ZAythj",
    "status": true,
}

I want to get the callback-url under Post in the json file above.. Please any idea on how to do that with any javascript Method.

ckeedee
  • 87
  • 2
  • 9
  • I agree with Brian McCutchon: 1) parse the HTTP response string into a JS object: `let jsonObject = JSON.parse(response.json());`, 2) Dereference balance.balance_callback: `let callbackUrl = jsonObject.balance.balance_callback;` – paulsm4 Nov 28 '20 at 05:43

2 Answers2

0

Let's say you call the date like that

fetch('urlOfTheApi')
.then( response => resonse.json()
.then( json => { 
   console.log(json);
});

So the solution is

fetch('urlOfTheApi')
.then( response => resonse.json()
.then( json => { 
   let callback_url = json.POST.callback;
   return fetch(callback_url, {method:'POST'}).
})
.then( () => console.log('ok')
.catch( console.error );
farvilain
  • 2,552
  • 2
  • 13
  • 24
0

Based on your JSON you should create an interface to define the object of the JSON and the particular part of the JSON that you need if you just need that property you could create the following interface

interface Response {
  Post: {
    callback_url: string;
  }
}

In the service where you are requesting the endpoint from your API, you set that this method returns a Response type of data. And inside of the subscription on your method you could access the property of the object of the JSON.