【发布时间】:2021-09-30 14:39:32
【问题描述】:
由于某种原因,我很难将此 txt 文件转换为实际的 javascript 数组。
myJson.txt
{"action": "key press", "timestamp": 1523783621, "user": "neovim"}
{"action": "unlike", "timestamp": 1523784584, "user": "r00k"}
{"action": "touch", "timestamp": 1523784963, "user": "eevee"}
{"action": "report as spam", "timestamp": 1523786005, "user": "moxie"}
目前我所拥有的不起作用
const fs = require('fs');
function convert(input_file_path) {
const file = fs.readFileSync(input_file_path, 'utf8');
const newFormat = file
.replace(/(\r\n\t|\n|\r\t)/gm,'')
.replace(/}{/g, '},{');
console.log([JSON.parse(newFormat)]);
}
convert('myJson.txt');
【问题讨论】:
-
你不能循环遍历它并以 [key: value, key: value,...] 的格式保存它
-
您的预期结果是什么?
[{ action: ...}, { action: ...}]? -
@MarcosCasagrande 是的,请。我对此感到非常沮丧,这让我很生气..lol
-
可能是因为输入的数据不是数组形式?
-
大括号表示一个对象,您正在查看数组,两种不同的数据类型。 (数组使用方括号)
标签: javascript node.js