You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript在HTML网站读取JSON文件并展示含图片的结果

JavaScript读取JSON并渲染网页实现指南

前置准备

你需要先在本地创建3个文件放在同一目录下:

  • data.json:内容使用你提供的JSON结构即可,可自行扩展多条result数据
  • index.html:页面代码文件
  • 对应路径的图片资源:比如JSON中写的apple.png,就把对应图片放在和HTML同级的目录

完整实现代码

index.html 代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>JSON数据展示</title>
    <style>
        /* 基础样式,可自行修改 */
        .result-card {
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 16px;
            margin: 12px 0;
            width: 350px;
        }
        .result-card img {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
        }
    </style>
</head>
<body>
    <h2>用户数据列表</h2>
    <!-- 数据渲染容器 -->
    <div id="data-container"></div>

    <script>
        window.onload = async function() {
            const container = document.getElementById('data-container');
            try {
                // 读取同目录下的JSON文件
                const response = await fetch('./data.json');
                const jsonData = await response.json();
                const resultList = jsonData.results;

                // 遍历数据拼接渲染内容
                let renderHtml = '';
                resultList.forEach(user => {
                    renderHtml += `
                    <div class="result-card">
                        <img src="${user.picture.large}" alt="${user.name.first}的头像">
                        <p>姓名:${user.name.first} ${user.name.last}</p>
                        <p>年龄:${user.date_of_birth.age}</p>
                        <p>出生日期:${new Date(user.date_of_birth.date).toLocaleDateString()}</p>
                    </div>
                    `
                })
                // 插入到页面
                container.innerHTML = renderHtml;
            } catch (error) {
                container.innerHTML = `<p style="color: red;">数据加载失败:${error.message}</p>`
                console.error('加载错误:', error);
            }
        }
    </script>
</body>
</html>

新手快速测试替代方案

如果不想搭建本地HTTP服务,可以直接把JSON数据写进JS变量,跳过fetch请求步骤,替换上面script标签里的代码即可:

window.onload = function() {
    const container = document.getElementById('data-container');
    // 直接赋值JSON数据
    const jsonData = {
        "number_of_results": 20,
        "results": [
            {
                "name": {
                    "first": "Test",
                    "last": "Test"
                },
                "date_of_birth": {
                    "date": "1985-12-03T02:05:33",
                    "age": 36
                },
                "picture": {
                    "large": "apple.png"
                }
            }
        ]
    };
    const resultList = jsonData.results;

    // 遍历渲染逻辑和之前一致
    let renderHtml = '';
    resultList.forEach(user => {
        renderHtml += `
        <div class="result-card">
            <img src="${user.picture.large}" alt="${user.name.first}的头像">
            <p>姓名:${user.name.first} ${user.name.last}</p>
            <p>年龄:${user.date_of_birth.age}</p>
            <p>出生日期:${new Date(user.date_of_birth.date).toLocaleDateString()}</p>
        </div>
        `
    })
    container.innerHTML = renderHtml;
}

注意事项

  • 本地直接打开HTML文件调用fetch会触发跨域报错,解决方法:使用VS Code的Live Server插件启动本地服务运行页面,或者用上面的直接写变量的方案测试
  • 图片要保证路径和JSON中picture.large字段写的一致,如果图片存放在img文件夹下,字段值要改成img/apple.png
  • 取值时注意JSON的层级结构,不要写错字段名,否则会出现undefined报错

内容的提问来源于stack exchange,提问作者Jeanlqs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 23:54:00