Home > OS >  How can I read remote json file into local array of objects?
How can I read remote json file into local array of objects?

Time:08-27

json file on server ('url') to read looks like this:

[{"name":"Belles, Josh", "rate":"1238", "id":"30091457"}, 
 {"name":"Capwell, Thomas", "rate":"1956", "id":"16761815"}, 
 {"name":"Craddock, Justin", "rate":"1587", "id":"14498573"}
]

function newFile(out) {alert(out); myArray = JSON.parse(out);}
// ALERT JUST SHOWS: [object Object],[object Object],[object Object],[object Object],[object Object]

fetch(url)
    .then(res => res.json())
    .then((out) => {
        console.log('Output: ', out); // THIS WORKS
    myArray = out; //WORKS
    alert(myArray[1].name); //WORKS
    console.log (JSON.stringify(myArray)); //WORKS
}).catch(err => console.error(err));

But any reference to myArray outside of the fetch doesn't see myArray.

Like this no longer works:

alert(myArray[1].name); 

How can I use myArray outside of the fetch ?

CodePudding user response:

Your out is already in JSON format, you don't need to parse it again.
Just do myArray = out

EDIT

As the question is little modified(For accessing the result outside fetch) you need to understand that fetch is a promise and it will assign the value to myArray after it gets resolved. A solution(with a callback getDataCompleted) to this is to do your operation inside then like:

fetch(url)
    .then(res => res.json())
    .then((out) => {
        console.log('Output: ', out); // THIS WORKS
       //myArray = out; //WORKS
        getDataCompleted(out);
}).catch(err => console.error(err));

function getDataCompleted(arr){
 //do something with arr
}

If you use myArray before fetch gets completed, myArray will not contain your expected results.

CodePudding user response:

fetch is asynchronous you need callback function to process the data later, but to get fetch result like synchronous, wrap your code in async block and use await

(async function() {

  function newFile(out) {
    console.log('title is: ', out.title)
  }
  
  let resp = await fetch('https://jsonplaceholder.typicode.com/todos/1')
  let myArray = await resp.json()
  newFile(myArray)
})();

or use <script [src=] type="module"> for modern browser

<script type="module">
function newFile(out) {
  console.log('title is: ', out.title)
}

let resp = await fetch('https://jsonplaceholder.typicode.com/todos/1')
let myArray = await resp.json()
newFile(myArray)
</script>

  • Related