【问题标题】:Svelte - Help to parse data from API - object jsonSvelte - 帮助从 API 解析数据 - 对象 json
【发布时间】:2021-07-25 03:51:51
【问题描述】:

我在显示从 API 获取的数据时遇到问题。

示例 json 数据:

{
"records": [
    {
        "event": {
            "type": "navigate"
        },
        "setup": {
            "attributes": {
                "title": "New Tab"
            },
            "description": "",
            "name": "",
            "type": null,
            "url": "chrome://newtab/"
        },
        "time": 1612271431271
    },
    {
        "event": {
            "type": "navigate"
        },
        "setup": {
            "url": "https://3.basecamp.com/signup/account/new?plan=one_v1"
        },
        "time": 1612271438035
    },
    {
        "event": {
            "type": "focus"
        },
        "setup": {
            "altPath": "article/form/section[1]/div[1]/input[@id='signup_full_name'][@name='signup[full_name]'][@type='text']",
            "altSelector": "article #signup_full_name",
            "attributes": {
                "autofocus": "autofocus",
                "class": "input session-fields__signup floating-placeholder__input",
                "id": "signup_full_name",
                "name": "signup[full_name]",
                "placeholder": "Your name",
                "rcrdr-extra-style": {
                    "display": "block",
                    "visibility": "visible"
                },
                "required": "required",
                "type": "text"
            },
            "computedRole": "textbox",
            "frame": "0",
            "frame_id": "0",
            "html": "<input class=\"input session-fields__signup floating-placeholder__input\" placeholder=\"Your name\" required=\"required\" autofocus=\"autofocus\" type=\"text\" name=\"signup[full_name]\" id=\"signup_full_name\">",
            "nodeName": "input",
            "nodeType": 1,
            "rootpath": "/html/body/main/div/section/article/form/section[1]/div[1]/input",
            "selector": "#signup_full_name",
            "xpath": "id(\"signup_full_name\")"
        },
        "time": 1612271489789
    }
]

}

我的目标是显示表格中的每个键,例如,输出应如下所示:

table

到目前为止我尝试过的是:


<script>
import { onMount } from "svelte";
   // Please, consider the data sample provided above.
  const apiURL =
    "http://localhost/electron/my-test/data.json";
  let recordsObject = [];
  let records;

  onMount(async () => {
    const response = await fetch(apiURL);
    if (response.status === 200) {
      console.log("Success");
      recordsObject = await response.json();
      records = JSON.stringify(recordsObject);
      //   console.log(recordsObject);
      console.log(records);
    } else {
      throw new Error(response.status);
    }
  });

</script>

<section>
  <ul>
    {#each [records] as record}
      <li>
        {record}
      </li>
    {/each}
  </ul>
</section>

我得到的输出是这样的:


{"records":[{"event":{"type":"navigate"},"setup":{"attributes":{"title":"New Tab"},"description":"","name":"","type":null,"url":"chrome://newtab/"},"time":1612271431271},{"event":{"type":"navigate"},"setup":{"url":"https://3.basecamp.com/signup/account/new?plan=one_v1"},"time":1612271438035},{"event":{"type":"focus"},"setup":{"altPath":"article/form/section[1]/div[1]/input[@id='signup_full_name'][@name='signup[full_name]'][@type='text']","altSelector":"article #signup_full_name","attributes":{"autofocus":"autofocus","class":"input session-fields__signup floating-placeholder__input","id":"signup_full_name","name":"signup[full_name]","placeholder":"Your name","rcrdr-extra-style":{"display":"block","visibility":"visible"},"required":"required","type":"text"},"computedRole":"textbox","frame":"0","frame_id":"0","html":"<input class=\"input session-fields__signup floating-placeholder__input\" placeholder=\"Your name\" required=\"required\" autofocus=\"autofocus\" type=\"text\" name=\"signup[full_name]\" id=\"signup_full_name\">","nodeName":"input","nodeType":1,"rootpath":"/html/body/main/div/section/article/form/section[1]/div[1]/input","selector":"#signup_full_name","xpath":"id(\"signup_full_name\")"},"time":1612271489789},{"event":{"type":"focus"},"setup":{"altPath":"article/form/section[1]/div[1]/input[@id='signup_full_name'][@name='signup[full_name]'][@type='text']","altSelector":"article #signup_full_name","attributes":{"autofocus":"autofocus","class":"input session-fields__signup floating-placeholder__input","data-sc-fieldtype":"FULL_NAME","data-sc-fieldtype-id":"160","id":"signup_full_name","name":"signup[full_name]","placeholder":"Your name","rcrdr-extra-style":{"display":"block","visibility":"visible"},"required":"required","type":"text"},"computedRole":"textbox","frame":"0","frame_id":"0","html":"<input class=\"input session-fields__signup floating-placeholder__input\" placeholder=\"Your name\" required=\"required\" autofocus=\"autofocus\" type=\"text\" name=\"signup[full_name]\" id=\"signup_full_name\" data-sc-fieldtype=\"FULL_NAME\" data-sc-fieldtype-id=\"160\">","nodeName":"input","nodeType":1,"rootpath":"/html/body/main/div/section/article/form/section[1]/div[1]/input","selector":"#signup_full_name","xpath":"id(\"signup_full_name\")"},"time":1612271498250} 

请问,有没有人可以帮我使用 svelte 在表格中显示输出?

谢谢。

编辑:

我已经更改了我的代码:

<script>
  const apiURL =
    ...src/Data/data.json";
  let recordsObject = [];
  let records = [];
  let results = {};

  let disabled = false;
  let promise = Promise.resolve([]);

  async function getDataFromApi() {
    const response = await fetch(apiURL);
    recordsObject = await response.json();
    records = recordsObject.records;
    // console.log(records);
    console.log(records.length);
    for (var i = 0; i < records.length; i++) {
      results[i] = records[i];
    }
    console.log(results);
    if (response.status === 200) {
      console.log("Success");
      //   console.log(recordsObject);
    } else {
      throw new Error(response.status);
    }
  }

  function handleClick() {
    promise = getDataFromApi();
    disabled = true;
  }
</script>

<button on:click={handleClick} {disabled}> Load Data </button>

{#await promise}
  <p>retrieving data...</p>
{:then results}
  <li>
    {#each [{ results }] as record}
      {record}
    {/each}
  </li>
{:catch error}
  <p style="color: red">{error.message}</p>
{/await}

现在输出很简单:

  • [对象对象]

请问,你知道我为什么会得到这个输出吗?

谢谢

【问题讨论】:

    标签: svelte


    【解决方案1】:

    我将指出一些应该有所帮助的事情,我强烈建议阅读以下内容:

    records 是一个字符串但应该是一个数组

    您的变量records 是一个字符串;我们可以在声明 records = JSON.stringify(recordsObject); 的行上看到这一点。

    因为它是一个字符串而不是一个数组,所以您正在使用{#each [records] as record} 将它转换为您的each 块中的一项的数组。从语法上讲,这是可行的,但这几乎肯定不是您想要的。您真正想要的是records 变量等于数组inside of json 响应。

    records = recordsObject.records
    

    如果您想知道为什么会这样,那么我强烈建议您进一步阅读 working with javascript objects

    表不是自动的

    每条记录都是一个 javascript 对象,本质上是一组键值对。 Svelte 不会自动将对象转换为表格,因为它不知道也不知道如何操作。这取决于您是否使用 HTML 进行格式化。

    所以,当你的代码中有这个时:

    <li>
      {record}
    </li>
    

    这只会吐出原始对象。您必须自己将其格式化为表格。我之前提供的 Svelte 每个块上的链接提供了一个小示例,说明如何开始执行该任务。

    对于您的具体情况,以下是如何将记录分解为不同部分的开始。

    <li>
      Type: {record.event.type}; Time: {record.time}
    </li>
    

    【讨论】:

    • 我对代码进行了一些更改,现在我收到错误消息:“未捕获的类型错误:无法读取未定义的属性‘事件’”。 &lt;script&gt; records = recordsObject.records; {#await promise} &lt;h1&gt;Loading...&lt;/h1&gt; {#each [{ records }] as { record }} &lt;li&gt; Type: {record.event.type}; Time: {record.time} &lt;/li&gt; {/each} {/await}我不明白为什么我得到未定义的“事件”。谢谢
    • 您用于each 的表达式不起作用。如果records 是一个数组,则不需要将其包装在[ ]{ } 中。这是我为展示这一点所做的回复:svelte.dev/repl/b8e71d9c607141c6bf51790f1882a6ee?version=3.40.2
    • 嗨@Auroratide。谢谢你,最后,我设法得到了数据。你的投入是决定性的。 [REPL] (svelte.dev/repl/e02d14a39108432ab534f7527a2e441b?version=3.40.2) 现在我将看看如何格式化这些数据。非常感谢
    猜你喜欢
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    相关资源
    最近更新 更多