loadJSON¶
From the p5js reference page
Reads the contents of a JSON file or URL and creates a JavaScript object (or array) with its values.
If a file is specified, it must be located in the sketch’s folder. The first parameter can also be a URL to JSON hosted online.
This method is asynchronous, meaning it may not finish before the next line in your sketch is executed. You can handle this with by use the async and await keywords, as shown below.
Starter Example (async/await)¶
let img;
async function setup() {
createCanvas(400, 400);
let json = await loadJSON("https://dog.ceo/api/breeds/image/random");
// console.log(json);
img = await loadImage(json.message);
}
function draw() {
image(img, 0, 0);
}
In this example:
loadJSON()gets JSON from a web API.The API returns an object with a
messageproperty that contains an image URL.loadImage()then loads that image so it can be drawn to the canvas.
Important Patterns to Know¶
Access object values with dot notation, for example
json.message.If JSON contains arrays, loop through them with
fororfor...of.Use
console.log(json)to inspect unknown JSON structures.
Demo¶
Use the Dog API endpoint https://dog.ceo/api/breeds/image/random.
Load JSON data in
setup().Extract the image URL from
json.message.Load and display the dog image on the canvas.
Add a mouse click (or key press) to fetch and show a new random dog.
Next Example: Weather Data by City¶
async function setup() {
createCanvas(400, 400);
await getWeather("Saskatoon");
}
function draw() {
background(220);
}
async function getWeather(cityName) {
// Find coordinates
let geoData = await loadJSON(`https://geocoding-api.open-meteo.com/v1/search?name=${cityName}&count=1`);
// console.log(geoData);
let lat = geoData.results[0].latitude;
let lon = geoData.results[0].longitude;
// Get weather
let weatherData = await loadJSON(`https://api.open-meteo.com/v1/gem?latitude=${lat}&longitude=${lon}¤t=temperature_2m&daily=temperature_2m_max,temperature_2m_min&timezone=auto`);
console.log(weatherData);
// console.log("Current:", weatherData.current.temperature_2m);
console.log("Today's High: " + weatherData.daily.temperature_2m_max[0]);
console.log("Today's Low: " + weatherData.daily.temperature_2m_min[0]);
}
In this example:
The first
loadJSON()call converts a city name into latitude/longitude.The second
loadJSON()call uses those coordinates to get forecast data.Nested fields and arrays are accessed with paths like
weatherData.daily.temperature_2m_max[0].
Demo¶
Use the weather example and turn it into a simple data visualization.
Request both temperature and humidity in
currentdata:current=temperature_2m,relative_humidity_2mSave both values to variables after loading weather JSON.
Make the background color in
draw()depend on the temperature.Draw a rectangle where the color depends on the humidity.
Final Example: ESPN Scores and Team Info¶
let homeLogo, awayLogo;
async function setup() {
createCanvas(400, 200);
let data = await loadJSON("https://site.api.espn.com/apis/site/v2/sports/basketball/nba/scoreboard");
let game = data.events[0].competitions[0];
let home = game.competitors.find(c => c.homeAway === "home").team;
let away = game.competitors.find(c => c.homeAway === "away").team;
homeLogo = await loadImage(home.logo);
awayLogo = await loadImage(away.logo);
}
function draw() {
background(220);
image(homeLogo, 50, 50, 100, 100);
image(awayLogo, 250, 50, 100, 100);
}
In this example:
loadJSON()gets the live NBA scoreboard feed from ESPN.The code drills into nested arrays/objects:
events[0] -> competitions[0] -> competitors.find(...)selects the home and away teams, then their logos are loaded withloadImage().
Demo¶
Try extending this ESPN example.
Display logos from a few games tonight instead of just one game. Loop through
data.eventsand load logos for each matchup you want to show.Switch to a different league by changing the API endpoint. For example, replace
nbawithnhl,mlb, orfootball/nflin the URL.Draw each matchup in a row (away logo vs home logo) with team abbreviations.