I am relatively new to extracting data from a JSON file to a HTML page. Please could someone help. When I try to extract data from the file shows.json, it shows up on my page when deployed as 'Undefined'.
Here is the code that I have used to extract the data from the JSON file and show it on a chosen page.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name=viewport content="width=device-width, initial-scale=1">
<title>TheTheatreJournal</title>
<link rel="stylesheet" href=styles.css>
<style>
@import url('https://fonts.googleapis.com/css2?family=Lobster&display=swap');
</style>
</head>
<body>
<h1>The Theatre Journal</h1>
<p>Welcome to The Theatre Journal App, a place where theatre lovers can document their favourite trips acting as a checklist</p>
<nav>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="Theatre.html">Shows</a></li>
<li><a href="Journal.html">Journal</a></li>
<li><a href="Tickets.html">Tickets</a></li>
<li><a href="Maps.html">Maps</a></li>
</ul>
</nav>
<div id="debug"></div>
<script>
fetch("shows.json")
.then (response => response.json())
.then (data =>{
console.log(data.Musical)
document.querySelector("#debug").innerText = data.Musical
console.log(data.Theatre)
document.querySelector("#debug").innerText = data.Theatre
console.log(data.City)
document.querySelector("#debug").innerText = data.City
console.log(data.About)
document.querySelector("#debug").innerText = data.About
console.log(data.ShowLogo)
document.querySelector("#debug").innerText = data.ShowLogo
})
</script>
</body>
</html>
shows.json file:
{
"shows": [
{
"Musical": "Wicked The Musical",
"Theatre": "Apollo Victoria",
"City": "London",
"About": "When Dorothy famously triumphed over the Wicked Witch of the West, we only ever heard one side of the story. Gregory Maguire‘s acclaimed 1995 novel, ‘Wicked: The Life and Times of the Wicked Witch of the West’, re-imagines the Land of Oz, creating a parallel universe to the familiar story written by L. Frank Baum and first published as ‘The Wonderful Wizard of Oz’ in 1900.",
"ShowLogo": "wickedthemusical"
},
{
"Musical": "Heathers The Musical",
"Theatre": "Theatre Royal Haymarket",
"City": "London",
"About": "How Very! Greetings, salutations. Welcome to Westerberg High, where Veronica Sawyer is just another of the nobodies dreaming of a better day. But when she’s unexpectedly taken under the wings of the three beautiful and impossibly cruel Heathers, her dreams of popularity finally start to come true. Until JD turns up, the mysterious teen rebel who teaches her that it might kill to be a nobody, but it’s murder being a somebody",
"ShowLogo": "heathersthemusical"
},
{
"Musical": "Waitress The Musical",
"Theatre": "Adelphi Theatre",
"City": "London",
"About": "Meet Jenna, a waitress and expert pie-maker who dreams of some happiness in her life. When a hot new doctor arrives in town, life gets complicated. With the support of her workmates Becky and Dawn, Jenna overcomes the challenges she faces and finds that laughter, love and friendship can provide the perfect recipe for happiness.",
"ShowLogo": "waitress"
},
{
"Musical": "Frozen The Musical",
"Theatre": "Theatre Drury Lane",
"City": "London",
"About": "Full of heart, humour and powerful storytelling, FROZEN will sweep you away to the magical world of Arendelle. Groundbreaking sets and special effects, exquisite costumes and innovative stagecraft combine to stunning effect in this unforgettable experience that will delight people of all ages.",
"ShowLogo": "frozen"
},
{
"Musical": "Six The Musical",
"Theatre": "The Arts Theatre",
"City": "London",
"About": "From Tudor Queens to Pop Princesses, the six wives of Henry VIII take to the mic to tell their tales, remixing five hundred years of historical heartbreak into a 75-minute celebration of 21st century girl power. These Queens may have green sleeves but their lipstick is rebellious red.",
"ShowLogo": "uktour"
}
]
}
I do not understand why the data is showing as undefined in both the console and on the page. Please can someone help me to resolve this issue, it would be much appreciated.
You can loop through the contents of the json using the .map()
function.
<script>
const fetchJson = async () => {
// Getting the content from the JSON file.
const response = await fetch("shows.json");
const { shows } = await response.json();
// Displaying the contents on the page.
document.querySelector("#debug").innerHTML = `
${shows.map(({Theatre, Musical, City, About, ShowLogo}) => `
${Theatre}<br>
${Musical}<br>
${City}<br>
${About}<br>
${ShowLogo}<br>
</div>
`)}`
}
fetchJson();
</script>
Notice that, as @mehowthe said, if you do document.querySelector("#debug").innerText = data.City
you'll be overwriting the data with the one that you're assigning to it, not appending it.
EDIT: Including images
Asuming you have a reference to the image logo in your JSON, url or path, like this:
"shows": [
{
// ...
"ShowLogo": "./assets/logo.png"
}
]
You could edit the code from before to add an img
tag with the reference to that path/url, like this
EDIT2: Removing the comma between elements
document.querySelector("#debug").innerHTML = `
${shows.map(({Theatre, Musical, City, About, ShowLogo}) => `
${Theatre}<br>
${Musical}<br>
${City}<br>
${About}<br>
// Creating an IMG tag with the path/url as src attribute
<img src=${ShowLogo} alt="${Theatre}" /><br>
</div>
// Removing the comma.
`).join("")}`
I've used the Theatre
property value as alt
attribute for the img, since it's unique and describes what's shown in the img in case for some reason it couldn't load. Isn't really required, but it is recommended.