【问题标题】:Extracting Data from a JSON file to HTML从 JSON 文件中提取数据到 HTML
【发布时间】:2021-06-06 14:36:55
【问题描述】:

我对从 JSON 文件中提取数据到 HTML 页面比较陌生。请有人帮忙。当我尝试从文件 show.json 中提取数据时,它会在部署为“未定义”时显示在我的页面上。

这是我用来从 JSON 文件中提取数据并将其显示在所选页面上的代码。

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 文件:

{
 "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"
   }
   
 ]
}

我不明白为什么数据在控制台和页面上都显示为未定义。请有人帮我解决这个问题,不胜感激。

【问题讨论】:

  • 请给我们展示shows.json
  • 添加了shows.json文件
  • 你不应该循环显示数组吗?类似 data.shows[i].Musical
  • 如果您的shows.json 是可访问的,那么您的data 是一个json 对象,具有shows 属性,其中包含您尝试访问的字段的对象数组。此外 - 对于每个分配 document.querySelector("#debug").innerText = data.Musical,您正在覆盖此标签的内容,而不是附加数据。因此,首先您需要了解数据的结构 - 为此您可以尝试使用以下语句显示“数据”值:document.querySelector("#debug").innerText =JSON.stringify(data)

标签: javascript html json extract


【解决方案1】:

您可以使用 .map() 函数循环遍历 json 的内容。

<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>

请注意,正如@mehowthe 所说,如果您执行document.querySelector("#debug").innerText = data.City,您将使用您分配给它的数据覆盖数据,而不是附加它。

编辑:包括图片

假设您在 JSON、url 或路径中有对图像徽标的引用,如下所示:

"shows": [
     {
      // ...
       "ShowLogo": "./assets/logo.png"
     }
 ]

您可以编辑之前的代码以添加一个 img 标记并引用该路径/url,如下所示

EDIT2:删除元素之间的逗号

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("")}`

我使用 Theatre 属性值作为 img 的 alt 属性,因为它是唯一的,并且描述了 img 中显示的内容,以防由于某种原因无法加载。不是必需的,但建议这样做。

【讨论】:

  • 非常感谢!这完美地工作。出于兴趣,我如何让图像工作,因为变量 ShowLogo 包含图像
  • @Woody98 我已经编辑了我的最后一个答案,看看。
  • 非常感谢您! - 只是出于兴趣,我将如何摆脱第二个和第三个选项音乐开头出现的逗号
  • .map() 方法之后添加.join(""),如下所示:shows.map(_map code here_).join("") 如果我不清楚,我也会编辑帖子。
猜你喜欢
  • 2017-04-03
  • 2019-01-22
  • 2016-11-23
  • 2018-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
相关资源
最近更新 更多