JavaScript 脚本 - 将 CSV 文件读取到 SVG 脚本中

问题描述 投票:0回答:2

我是 JavaScript 新手,我正在尝试改编用于显示 SVG 图像的脚本。

当前脚本读取脚本内的值表单,我想对其进行调整以从 CSV 文件中读取值。我遇到的问题是脚本似乎无法正确解释该值。我遇到问题的列是“nodeStyle”。如果我将列变量从 nodeStyle 更改为 {width:100,height:100} 它可以工作,但不会从 CSV 文件中读取它。任何帮助都会很棒

// 数据.CSV 格式
// id、x、y、href、nodeStyleW、nodeStyle、属性、label_text
// NODE22,650,50,/icon.png,{宽度:100,高度:100},,NODE22

   fetch('/data.csv')
     .then(response => response.text())
     .then(data => {

       const rows = data.split('\n').slice(1); // Skip header row
         rows.forEach(row => {
           const [id, x, y, href, nodeStyle, properties, label_text] = row.split(/,(?![^{]*})/);

           net.addNode(id, parseInt(x), parseInt(y), href, nodeStyle, properties, label_text);
         });
     });

   // Mode added via script
   net.addNode("NODE2", 600, 50, "/images/icon.png", {width: 100, height: 100}, "", "", "NODE2");

我尝试直接添加该值,这有效:

net.addNode(id, parseInt(x), parseInt(y), href, nodeStyle, properties, label_text);
net.addNode(id, parseInt(x), parseInt(y), href, {width: 100, height:100}, properties, label_text);
javascript regex csv constants fetch-api
2个回答
0
投票

您在正确解析 CSV 文件中的 nodeStyle 时似乎遇到了问题。问题可能在于您如何在 CSV 中表示 nodeStyle 以及如何在 JavaScript 代码中解释它。

在您的 CSV 文件中,您似乎试图将 nodeStyle 表示为对象,但 CSV 本身并不支持像 JavaScript 对象 这样的嵌套结构。因此,您需要为 nodeStyle 找到合适的表示形式,以便可以在 JavaScript 代码中轻松解析。

一种方法可能是将 nodeStyle 表示为您稍后可以在 JavaScript 代码中解析的格式的字符串。例如,而不是写

{宽度:100,高度:100}

直接在 CSV 中,您可以将其表示为 JSON 字符串,例如

“{“宽度”:100,“高度”:100}”

以下是如何修改代码来实现此目的:

fetch('/data.csv')
  .then(response => response.text())
  .then(data => {
    const rows = data.split('\n').slice(1); // Skip header row
    rows.forEach(row => {
      const [id, x, y, href, nodeStyleStr, properties, label_text] = row.split(/,(?![^{]*})/);
      const nodeStyle = JSON.parse(nodeStyleStr); // Parse the nodeStyle string to an object

      net.addNode(id, parseInt(x), parseInt(y), href, nodeStyle, properties, label_text);
    });
  });

经过此修改,您的 CSV 将如下所示:

id, x, y, href, nodeStyleW, nodeStyle, properties, label_text
NODE22,650,50,/icon.png,"{""width"":100,""height"":100}",,NODE22

这样,您可以将 nodeStyle 表示为 CSV 中的 JSON 字符串,然后将其解析回 JavaScript 代码中的对象,然后再将其传递给 net.addNode()。这应该可以解决您从 CSV 正确解释 nodeStyle 的问题。

祝你好运!


-1
投票

已解决:更改代码解决了问题。我只需要将 CSV 文件修改为 {"width": 100, "height": 100}

© www.soinside.com 2019 - 2024. All rights reserved.