0

I'm attempting to fetch an API that has 2 variables I need out of hundreds. How do I get just these 2 variables and assign them to variables in a function?

When I do

 fetch( " https://genericAPI.com" )
.then( response => response.json() )
.then( json => console.log( json ) );

The log is full of all these variables I mentioned about, but I don't know how to single the 2 I need out and assign them to other variables. I've done this in java by doing the following

    JSONObject myResponse = new JSONObject(response.toString());

    String end = myResponse.getString("endAt");
    String beg = myResponse.getString("startAt");

I've been looking everywhere for a guide on how to do this, but I think I'm using the incorrect terminology so I can't find an answer

Here's part of what's returned, endAt is one in particular I'm trying to grab

{"endAt": "1533797999000",
  "exchangeEndAt": "1534748399000",
  "enableFlag": true,
  "publicEndAt": "1533949199000",
  "distributionStartAt": "1533848400000",
  "eventId": 14,
  "rankingRewards":...
)  
Phil Cooper
  • 3,083
  • 39
  • 63
Josh
  • 164
  • 4
  • 16
  • Here's part of what's returned, endAt is one in particular I'm trying to grab `{"endAt":"1533797999000","exchangeEndAt":"1534748399000","enableFlag":true,"publicEndAt":"1533949199000","distributionStartAt":"1533848400000","eventId":14,"rankingRewards":` – Josh Aug 08 '18 at 22:58
  • the upshot is, you do not want to `parse only part of JSON` - you parse the whole lot, then access the properties as you would a regular javascript object - because once you parse JSON, you end up with a regular javascript object – Jaromanda X Aug 08 '18 at 23:00

2 Answers2

1

You're on the right path

fetch( " https://genericAPI.com" )
.then( response => response.json() )
.then( json => {
    let end = json.endAt
    let beg = json.startAt
});
  • That does indeed work, but it looks like end and beg aren't being assigned any value, I'm getting an `Uncaught ReferenceError: end is not defined at :1:1` error when calling end or beg in the console. I removed the `let` from the variables, and it's working now. Is that all I needed? – Josh Aug 08 '18 at 23:00
  • The let would work if you processed the fields where the let were – mplungjan Aug 08 '18 at 23:06
  • variables defined using the `let` keyword are scoped to the current block. That means if you try to access `end` and `beg` outside of the current `then` callback block, it would throw an undefined error. One solution to this would be to declare `end` and `beg` outside of the then block – Chinonso Chukwuogor Aug 08 '18 at 23:08
0

Perhaps you're looking for an async function?

async function getTwoVariables() {
  const response = await fetch('https://genericAPI.com').then(res => res.json());
  const end = response.endAt;
  const beg = response.startAt;
  console.log(end, beg);
  // or some other stuff
}
Coalpha
  • 31
  • 4