如何在Node JS中读取文本文件并将其作为JSON对象返回? [英] How to read a text file and return it as a JSON object in Node JS?
问题描述
我有一个文本文件.我需要读取函数中的文件并将其作为JSON对象返回.以下引发错误"JSON中位置0处的意外令牌V".
I have a text file. I need to read the file inside a function and return it as a JSON object. The following is throwing an error "Unexpected token V in JSON at position 0" .
Server.js
fs.readfile('result.txt', 'utf8', function(err,data) {
if(err) throw err;
obj = JSON.parse(data);
console.log(obj);
});
result.txt如下所示
result.txt looks like the following
VO1:10 5 2
VO1: 10 5 2
VO2:5 3 2
VO2: 5 3 2
我认为我不能直接使用JSON.parse.我该如何进行?
I think I cannot use JSON.parse directly. How do I proceed?
推荐答案
假设以下内容:
每行用换行符(
\ n
)
每行用:
分隔,其中前面的部分是键,后面的部分是
(空格)分隔的字符串,应指示将值作为数组键.
Every line is separated by a :
where the part in front of it is the key and the part behind it is a
(space) separated string that should indicate the keys values as an array.
以下应适用于您的格式:
Below should work for your format:
fs.readfile('result.txt', 'utf8', function(err,data) {
if(err) throw err;
let obj = {};
let splitted = data.toString().split("\n");
for (let i = 0; i<splitted.length; i++) {
let splitLine = splitted[i].split(":");
obj[splitLine[0]] = splitLine[1].trim();
}
console.log(obj);
});
这篇关于如何在Node JS中读取文本文件并将其作为JSON对象返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!