如何将txt文件数据转换成json?

How to convert txt file data to json?

我正在尝试使用 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 

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

readFileSync不return承诺。通过删除 await 来修复它。这是一个 Sync 方法,因此它将等到它完成。

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

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

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

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