0

I am guessing my terminology in the following post is wrong. I am generally new to using APIs.

I am using an API from the Census Bureau that returns a list of of objects in JSON format. The issue I am having with this particular API is that it appears the arrays are nested within arrays that don't have names or any way to find a path through to the object.

Here is what the API query returns:

[
[
"DRRALL",
"CRRINT",
"RESP_DATE",
"CRRALL",
"GEO_ID",
"DRRINT",
"state"
],
[
"0.4",
"37.1",
"2020-04-10",
"41.4",
"0400000US36",
"0.4",
"36"
]
]

I am trying to obtain the date the information was queried and the response rate, but I just have never see JSON in this format. I checked to make sure it is valid JSON, and it is. I tried peeling away layer by layer, but I end up with undefined or empty arrays when attempting to push it to another variable.

Here is as close as I've gotten to the desired results:


fetch(url)
  .then((resp) => {
    return resp.json();
  })

  .then((data) => {
    stateArray.push(data[1]);
  });

console.log(stateArray);

Here's the result of my console log:

[]
​0: (7) […]
​​0: "0.4"
​​1: "37.1"
​​2: "2020-04-10"
​​3: "41.4"
​​4: "0400000US36"
​​5: "0.4"
​​6: "36"
length: 7
<prototype>: Array []
length: 1

As you'll see, there is another empty array just before the array with my desired objects.

Any help would be great.

Thanks!

1
  • Is that the whole content of your json file? Commented Apr 10, 2020 at 19:59

2 Answers 2

1

fetch function returns Promise which returns data asyncronously. At the moment when you invoke console.log(stateArray) Promise is not returned data yet. Move console.log(stateArray) into then statement:

fetch(url)
  .then((resp) => {
    return resp.json();
  })

  .then((data) => {
    stateArray.push(data[1]);
  })
.then(data => console.log(stateArray));
Sign up to request clarification or add additional context in comments.

2 Comments

I could get that to work locally, but I have to pull multiple API queries for US, City and Counties as well so I was hoping to push them all global. Is that just not possible?
If you need several requests executed alltogether you can try to compose an array of requests and use Promise.all the get all the data thogether. And in then block after Promise.all() you can add all the data at once.
0

It is valid JSON; its an array of arrays.

Maybe using the spread operator (stateArray.push(...data[1])) will push the JSON's arrays to stateArray.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.