簡體   English   中英

在 Javascript 中拉取 JSON 數據

[英]Pulling JSON data in Javascript

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

I am actually creating 9 cards using flex in css.I have used static data but now I have to use dynamic data from JSON file.As I am newbie in typescript,I want your help to render json file in flex container.I have given上面 1 張卡的 JSON 文件片段。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,這使我的進度停止了。 請幫幫我。

讀取 JSON

為了能夠解析 .json 文件,您需要確保在 tsconfig.json 的"compilerOptions"部分中有"resolveJsonModule": true 這允許您導入 JSON object。

import json from "./data.json";

導入的 object 將正確推斷所有類型。 您實際上可以使用 object 來派生類型聲明。

const issues = json.issues;

type Issue = typeof issues[number];

執行腳本

我們將定義一個 function 將卡片插入 DOM(DOM 是 HTML 代碼的 object 表示)。 我們需要以某種方式將其稱為function。 有很多方法可以做到這一點。 您可以使用立即調用的 Function 表達式 (IIFE) 將變量排除在全局 scope 之外。 您可以將 function 作為事件偵聽器添加到 DOMContentLoaded 事件等。

我只是在文件的頂層調用 function,因為我沒有在這里進行任何構建步驟。 function 將在加載"main.ts"時運行。 我通過 HTML 中的script標簽加載它。

索引.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創建每個元素,設置其屬性,並將 append 通過調用所需父級的parent.appendChild將其添加到 DOM。

您可以在一個 function 中完成所有這些操作,但我喜歡將代碼分解為多個部分。 我們有一個 function createCard接受一個Issue並返回一個HTMLDivElement 然后我們有一個 function 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();

代碼沙盒鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM