如何将txt文件数据转换为json?
Posted
技术标签:
【中文标题】如何将txt文件数据转换为json?【英文标题】:How to convert txt file data to 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
【参考方案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 因为它是这样工作的。它返回undefined
。 nodejs.org/dist/latest-v16.x/docs/api/…
是的,writeFileSync
不返回文件的内容。以上是关于如何将txt文件数据转换为json?的主要内容,如果未能解决你的问题,请参考以下文章
将其字段中带有逗号的 .csv 文件转换为 JSON/TXT