【问题标题】:How to convert txt file data to json?如何将txt文件数据转换为json?
【发布时间】:2022-01-23 02:51:11
【问题描述】:

我正在尝试使用 fs 方法将 txt 文件转换为 json,它会抛出错误 omething is wrong TypeError: data.split is not a function 此处实施错误

index.js

 try {
    let data = await fs.readFileSync(path.join(filePath));
    const obj = {
      User: "",
      User: Location: "",
      Company Name: "",
      Notes: " "
  };
    const content = [];
    data.split("\n").map((line) => {   
          if (line.startsWith("User:")) {
              obj.title = line.substring(6);
          } else if (line.startsWith("Company Name:")) {
            obj.title = line.substring(6);
          } else if (line.startsWith("User Location:")) {
            obj.tags = line.substring(4).split(",");
          } else if (line.startsWith("Notes:")) {
            obj.tags = line.substring(4).split(",");
          }   else {
                content.push(line);
            }
    });
    obj.content = content.join("\n");
    const finalres = fs.writeFileSync("output.json", JSON.stringify(obj));
    console.log("Final>>>>>>", finalres);
    res.send(finalres);
  } catch(e) {
    console.log("something is wrong", e);
  }

doc.txt

User: Account Admin

User Location:  New York, NY

Company Name: WeightWatcher

Notes:  Enabling growth through experimentation and analysis to 
      build a world-class onboarding experience
     Building and managing monitoring, configuration, control 
     plane, and operational services to allow 

【问题讨论】:

  • 那么什么是数据? console.log(data)
  • @epascarello 数据打印为缓冲区 [0] DATA
  • data..toString().split()
  • 现在改变了它的印刷最终>>>>>> undefined

标签: javascript node.js fs


【解决方案1】:

 await fs.readFileSync(path.join(filePath));

readFileSync 不返回承诺。通过删除await 来修复它。这是一个Sync 方法,所以它会等到它完成。

readFileSync 也将返回缓冲区。您可以将缓冲区转换为字符串或添加如下选项:

fs.readFileSync(path.join(filePath),{encoding:'utf8'});

还将对象修复为有效的 json 表示法:

    const obj = {
      User: "",
      "User Location": "",
      "Company Name": "",
      Notes: ""
  };

【讨论】:

  • 现在正在重新调整字符串但是最终 obj 仍在打印 [0] Final>>>>>> undefined
  • @hussain 因为它是这样工作的。它返回undefinednodejs.org/dist/latest-v16.x/docs/api/…
  • 是的,writeFileSync 不返回文件的内容。
猜你喜欢
  • 2017-02-09
  • 1970-01-01
  • 1970-01-01
  • 2017-06-18
  • 2023-03-16
  • 1970-01-01
  • 2022-01-10
  • 2021-12-20
  • 2020-11-09
相关资源
最近更新 更多