Explain Codes LogoExplain Codes Logo

How to get JSON from URL in JavaScript?

javascript
async-await
error-handling
fetch-api
Alex KataevbyAlex Kataev·Feb 18, 2025
TLDR

Get straight to retrieving JSON data from a URL using fetch with async/await:

async function getJSON(url) { const response = await fetch(url); if (!response.ok) throw new Error("Whoopsie daisy! Network response was not ok :("); return await response.json(); } // Call (async () => { try { console.log(await getJSON('https://api.example.com/data')); } catch (error) { console.error("It's not you, it's the data. Error:", error); } })();

Execute the getJSON() function by inserting your desired API endpoint and pump out your fetched JSON using console.log. Don't sweat the errors! They roll off easily with a try/catch block.

Expand your access skills

Becoming a JSON-fetching Sensei requires more than just the basics. Behold! Here are some advanced techniques for your JavaScript toolbox:

Ninja-style error handling

Slice through bugs, cut down errors. Create reusable functions with bulletproof error handling:

const ninjaFetch = async (url) => { try { const response = await fetch(url); if (!response.ok) throw new Error(`HTTP Error! Status: ${response.status}`); return await response.json(); // Parsing the JSON like a pro } catch (error) { console.error("Well, this is awkward...Could not fetch data:", error); } }; // Time to fetch, ninja style! ninjaFetch('https://api.example.com/data');

Ancient browser wisdom

Use the ancient technique of a polyfill to bestow the wisdom of the Fetch API onto older browsers:

if (!window.fetch) { window.fetch = fetchPolyfill; // Teaching old browsers new tricks }

jQuery dojo tricks

In the dojo of jQuery, quick JSON-fetching katana strikes!

$.getJSON('https://api.example.com/data', function(data) { console.log(data); // Look Mom, no hands! });

Nostalgic XMLHttpRequest fallback

When fetch is on vacation, employ the tried-and-true XMLHttpRequest as your loyal henchman:

function getJSONWithXHR(url, callback) { const xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'json'; xhr.onload = function () { const status = xhr.status; if (status === 200) { callback(null, xhr.response); } else { callback(status, xhr.response); } }; xhr.send(); }

Node.js express delivery

Server-side JavaScript on Node.js works in similar ways:

const fetch = require('node-fetch'); async function getNodeJSON(url) { const response = await fetch(url); // rest of the code is as reliable as your pizza delivery at midnight }

Crossing domains, like a boss

When delivering data from a foreign domain, CORS (Cross-Origin Resource Sharing) is your visa:

fetch('https://api.otherdomain.com/data') .then(crossBorderResponse) .catch(immigrationControl);

Fast & Furious with arrow functions

Arrow functions make your code fast, furious, and tidy:

fetch('https://api.example.com/data') .then(res => res.json()) // Step aside traditional functions, it's arrow time! .then(data => console.log(data)) .catch(error => console.error("Oopsie! Error:", error));

Enhanced readability, DRY code

Keep your code cleaner than a whiteboard on Monday morning:

URLs as constants

Tuck away your endpoints in neat constants or variables:

const DATA_URL = 'https://api.example.com/data.json'; // DRY for the win!

Formatting Async/Await

Async functions can be as organized as your sock drawer:

async function printJSON(url) { try { const data = await getJSON(url); console.log(data); // Loud and proud } catch (error) { console.error("We've got a code bleeder! Error:", error); } }

Debug with console.log

Best buddies with console.log? You bet:

console.log('Data from the other side:', data);