How to get JSON data from a website

$.getJSON(“some url here”, function(JSONdata){})

Generally speaking I think I get how this code works. However; I had a few questions about the URL.

Can i get all the JSON data from a website by simply passing in the normal URL? I’ve noticed a consistent use of URL’s ending in .json;
If I have to pass a websitesURL.json for a specific website how do i find that websitesURL.json?

You’ll need a URL that resolves to a JSON file (that’s why they usually end with .json).

Usually you’ll find API information on the website.

1 Like

Just to be clear, it doesn’t need to address an actual JSON file directly. It could be that or it could be an API route on a web server that serves up JSON files/data.

In other words, if you just start using $.getJSON to random web addresses, they aren’t going to be sending back json data.

To make it clearer, here are an example of each:

var staticUrl = 'https://ksjazzguitar.github.io/data/techs.json';
$.getJSON(staticUrl, function(data) {
  console.log("This is an example of a static JSON file being served by a web server.")
  console.log(data);
});


var dynamicUrl = 'https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139';
$.getJSON(dynamicUrl, function(data) {
  console.log("This is an example of a dynamic JSON file being served by a web server.")
  console.log(data);
});

The first one is from my current portfolio site. There is a file I created called techs.json that is in that directory. Because it is a public directory, the server says, “OK, this directory is public so anyone is allowed to read it, he asked for that file by name, so I can just send this file back to his browser as JSON data.”

The second example is from FCC’s Glitch weather API. There isn’t a JSON file for every longitude and latitude combination, being generated once every minute - that would be insane. There is no actual JSON file on the server I am accessing. Instead, the server at fcc-weather-api.glitch.me sees a request coming in at the route api/current with parameters of lat and lon with those values. It is programmed to do the necessary calculations to dynamically generate the data, which it organizes into an object that gets sent back to your browser in real time as JSON. (Actually, there is another step where the FCC API calls another API, but let’s not make it more confusing than it needs to be.)

So there are two ways a JSON file can be served to you. What is the difference? On your end, not much, except that the dynamic one may change over time and with different parameters. For a static file, there are no parameters and it is always the same (unless the server keeps overwriting it with new data.)

This will all make more sense once you start doing the backend and start creating APIs yourself.

8 Likes