'Get json data from url and put it into variable by JavaScript

I have a JSON data in a URL, I want to get all JSON data from the URL by JavaScript (without jQuery) and put it into variable tags.

JSON Data:

 [
  {
    "uniq":"AXk2_U9l"
  },
  {
    "uniq":"AX0apLOG"
  },
  {
    "uniq":"AXrGmWk4"
  },
  {
    "uniq":"AXID1Psx"
  },
  {
    "uniq":"vovs2aPlj"
  }
]

And my JavaScript code, this code does not work:

async function get() {
  let url = 'https://jsonware.com/json/abfe005c41c8214e22e487b8d6eff417.json'
  let obj = await (await fetch(url)).json();
  console.log(obj);
}
var tags = get();

if there is a new method, please show.



Solution 1:[1]

You can do it using XMLHttpRequest like as follows

function loadJson() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     var tags = JSON.parse(this.responseText);
     console.log(tags);
    }
  };
  xhttp.open("GET", "https://jsonware.com/json/abfe005c41c8214e22e487b8d6eff417.json", true);
  xhttp.send();
}
loadJson();

Solution 2:[2]

Your call is not resolved asynchronously so tags are empty

Here is the standard way to use fetch:

fetch('https://jsonware.com/json/abfe005c41c8214e22e487b8d6eff417.json')
  .then(
    response => {
      if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' +
          response.status);
        return;
      }

      // Examine the text in the response
      response.json().then(function(data) {
        console.log(data);
      });
    })
  .catch(err => console.log('Fetch Error :-S', err));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shijin TR
Solution 2