【问题标题】:Pulling JSON data in Javascript在 Javascript 中提取 JSON 数据
【发布时间】:2021-06-13 03:53:37
【问题描述】:
{
    "issues": [
      {
        "id": "PCG8363042",
        "title": "Lorem ipsum dolor sit",
        "description": "Lorem ipsum dolor sit amet, conctetur adipiscing elit. Ut ut gravida dolor. Phasellus vitae sem.",
        "detailTitle": "Lorem ipsum dolor sit amet, conctetur adipiscing elit. Sed eu consectetur erat.",
        "reporter": "Sijo M Peter",
        "assignee": "Sijo M Peter",
        "assignee_desig": "UI/UX Designer",
        "type": "Task",
        "priority": "High",
        "status": "New",
        "resolution": "Unresplned",
        "fix_versions": "None",
        "affects": "None",
        "components": "None",
        "labels": "Webetc",
        "sprint": "C",
        "story_points": 6,
        "created": "01/02/2019",
        "updated": "01/02/2019",
        "votes": 0,
        "watchers": 1
      },

我实际上是在 css 中使用 flex 创建 9 张卡片。我使用了静态数据,但现在我必须使用 JSON 文件中的动态数据。由于我是 typescript 的新手,我希望你能帮助我在 flex 容器中渲染 json 文件。我已经为上面的 1 张卡片给出了 JSON 文件的 sn-p。下面给出了 flex 容器的卡片:

<div class="flex-container" >
  <div>
    <h3>ID:PCG30456</h3><span style="float:right;">January 02,2019</span>
    <h2>Lorem Ipsur dolor sit</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus malesuada diam faucibus. </p>
    <span>Assignee</span><span>Status</span>
    <img src="user_1.svg"><span>Sijo M Peter</span>
    <button>High Priority</button>
  </div>

我想为这 9 张卡片提取 JSON 代码。我刚刚启动了 javascript,这使我的进度停止了。请帮帮我。

【问题讨论】:

  • 确保"resolveJsonModule": true 位于tsconfig.json 文件的"compilerOptions" 部分,以便读取.json 文件。您将得到正确推断的所有类型。您在寻找纯打字​​稿吗?不是 React、Angular 等?如果没有帮助程序,创建 HTML 代码真的很烦人。您必须使用document.createElement 创建每个元素并设置其属性。那部分只是JS,不会随TS变化。
  • @LindaPaiste 是的,我明白了。但是你能帮我处理 JS 代码吗..即使那会很有帮助。

标签: javascript html css typescript


【解决方案1】:

读取 JSON

为了能够解析 .json 文件,您需要确保在 tsconfig.json 的 "compilerOptions" 部分中有 "resolveJsonModule": true。这允许您导入 JSON 对象。

import json from "./data.json";

导入的对象将正确推断出所有类型。您实际上可以使用该对象来派生类型声明。

const issues = json.issues;

type Issue = typeof issues[number];

执行脚本

我们将定义一个将卡片插入 DOM 的函数(DOM 是 HTML 代码的对象表示)。我们需要以某种方式调用该函数。有很多方法可以做到这一点。您可以使用立即调用函数表达式 (IIFE) 将变量排除在全局范围之外。您可以将您的函数作为事件侦听器添加到 DOMContentLoaded 事件等中。

我只是在文件的顶层调用函数,因为我没有在这里执行任何构建步骤。加载"main.ts" 时,该函数将运行。我通过 HTML 中的 script 标记加载它。

index.html

<!DOCTYPE html>
<div id="card-container" class="flex-container" />
<script type="module" src="./main.ts"></script>

用 Javascript 创建 HTML

在纯 Javascript/Typescript 中创建和添加元素到 DOM 非常冗长和烦人。很多人使用 React、Angular 等库来简化它。

您必须使用document.createElement 创建每个元素,设置其属性,并通过在其所需父级上调用parent.appendChild 将其附加到DOM。

您可以在一个函数中完成这一切,但我喜欢将代码分解为多个片段。我们有一个函数createCard,它接受Issue 并返回HTMLDivElement。然后我们有一个函数insertIssues,它从 JSON 中循环遍历数组并为每个问题插入一张卡片。

main.ts

import json from "./data.json";

const issues = json.issues;

// derive type declaration based on the json variable
type Issue = typeof issues[number];

// helper function creates a card element for one issue
// return type is inferred as HTMLDivElement
const createCard = (issue: Issue) => {
    // create card div
    const div = document.createElement("div");
    // create h3 with id
    const h3 = document.createElement("h3");
    h3.innerText = `ID:${issue.id}`;
    div.appendChild(h3);
    // create span with date
    const date = document.createElement("span");
    date.style.float = "right"; // can set style properties
    date.innerText = new Date(issue.created).toDateString();
    // create h2 with title
    const h2 = document.createElement("h2");
    h2.innerText = issue.title;
    div.appendChild(h2);

    // TODO: add other fields

    // return the composed card div element
    return div;
};

const insertIssues = () => {
    const target = document.getElementById(
        "card-container",
    );
    // in case no target was found
    if (!target) {
        console.log("no target container");
        return;
    }
    // create an element for each issue
    const cards = issues.map(createCard);
    // append each card to the target element
    // need to use an arrow function, cannot do cards.forEach(target.appendChild);
    cards.forEach((card) => target.appendChild(card));
};

// invoke the function
insertIssues();

Code Sandbox Link

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    • 2021-09-22
    • 2017-06-26
    相关资源
    最近更新 更多