"New to programming" I have a CSV file at http://vhost11.lnu.se:20090/assig2/data1.csv
“编程新手”我在http://vhost11.lnu.se:20090/assig2/data1.csv上有一个CSV文件
I am trying to convert it to a local json file. My code below.
我试图将其转换为本地json文件。我的代码如下。
I am getting {"X":"153","Y":"21","time":"21438"}}
value in my data1.json
.
我在我的data1.json中得到{“X”:“153”,“Y”:“21”,“time”:“21438”}}值。
const request=require('request')
const csv=require('csvtojson')
const fs = require('fs')
csv()
.fromStream(request.get('http://vhost11.lnu.se:20090/assig2/data1.csv'))
.on("json",function(jsonObj){ //single json object will be emitted for each csv line
console.log(jsonObj);
fs.writeFile("./data1.json", JSON.stringify(jsonObj), (err) => {
if (err) {
console.error(err);
return;
};
});
});
Where did I go wrong?
我哪里做错了?
1 个解决方案
#1
0
The callback function in the on
event is called for each line. You'll want to initialize an empty list in the outer most scope and push jsonObj to it from the callback in on
. You can then write your list to a file when the input file is done being read by handling the done
event.
每个行都会调用on事件中的回调函数。您将要在最外层的范围内初始化一个空列表,并从onback中的回调中将jsonObj推送到它。然后,当通过处理完成事件读取输入文件时,可以将列表写入文件。
#1
0
The callback function in the on
event is called for each line. You'll want to initialize an empty list in the outer most scope and push jsonObj to it from the callback in on
. You can then write your list to a file when the input file is done being read by handling the done
event.
每个行都会调用on事件中的回调函数。您将要在最外层的范围内初始化一个空列表,并从onback中的回调中将jsonObj推送到它。然后,当通过处理完成事件读取输入文件时,可以将列表写入文件。