Node.js:将文本转换为JSON

5

由于某些原因,我在将此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,...]的格式吗? - iceveda06
你期望的结果是什么?[{ action: ...}, { action: ...}] - Marcos Casagrande
@MarcosCasagrande 好的,请帮我看一下。这个问题真的让我很沮丧,笑死我了... - Victor Le
是因为输入数据不是数组形式吗? - J-Cake
花括号表示一个对象,你正在看数组,这是两种不同的数据类型。(数组使用方括号) - J-Cake
显示剩余5条评论
4个回答

5

由于您的文件每行包含一个JSON对象,因此您可以使用readline逐行读取该文件。

然后解析每一行,并将其推入一个数组中,在文件完全读取后返回(解析)该数组。

'use strict';

const fs = require('fs');
const readline = require('readline');

function convert(file) {

    return new Promise((resolve, reject) => {

        const stream = fs.createReadStream(file);
        // Handle stream error (IE: file not found)
        stream.on('error', reject);

        const reader = readline.createInterface({
            input: stream
        });

        const array = [];

        reader.on('line', line => {
            array.push(JSON.parse(line));
        });

        reader.on('close', () => resolve(array));
    });
}


convert('myJson.txt')
    .then(res => {
        console.log(res);
    })
    .catch(err => console.error(err));

3
我会这样做

var fs = require('fs');
var readline = require('readline');
var array = [];
var input = null;
var rd = readline.createInterface({
    input: fs.createReadStream(__dirname+'/demo.txt')
    
});

rd.on('line', function(line) {
    array.push(JSON.parse(line));
});
rd.on('close', function(d){
  array.forEach(e=>console.log(e.action))
})

这里正在发生的事情是,我使用nodejs的核心模块之一readline依次读取文件中的每一行。监听事件并执行所需操作。
嗯,你肯定需要将每行解析为JSON ;)
谢谢

0
在脚本中我正在做的是逐行读取文本文件的内容,并将其存储到数组中,同时将其转换为JSON对象。当我们到达最后一行并且我们的JSON数组/对象具有所有数据时。现在,您可以使用JSON.stringify()将JSON对象转换为字符串,然后使用fs.writeFileSync()将此对象写入新文件中。
注意:- 您必须安装Line reader包,即npm install line-reader
var lineReader = require('line-reader');
var fs = require('fs')

var jsonObj = {};
var obj = [];
var file = "fileName.json"
var num= 0;

lineRead();
async function lineRead(){
lineReader.eachLine('input.txt', function(line, last) {
// to check on which line we're.
      console.log(num);
      num++;
      convertJson(line)

      if(last){
//when it's last line we convert json obj to string and save it to new file.
        var data = JSON.stringify(obj)
        fs.writeFileSync(file,data);

      }
});
}

function convertJson(data){
        var currentVal = data
        var value = JSON.parse(data)
        var temp = value;
//storing the value in json object
        jsonObj = value;
        obj.push(jsonObj);
    }
  
}

0
你的代码问题在于你试图将JS数组解析为JSON数组,而JSON数组字符串应该只是字符串。
这是你试图做的事情:
jsArray = ['{"foo": "bar"}, {"foo":"baz"}']

这是一个有效的JS数组,包含单个字符串值'{"foo": "bar"}, {"foo":"baz"}'。

jsonArrayStr = '["{"foo": "bar"}, {"foo":"baz"}"]' 

这是一个有效的JSON数组字符串(因为方括号是字符串的一部分)。

为了使您的代码运行,您需要在解析之前将方括号添加到字符串中。

function convert(input_file_path) {
    const file = fs.readFileSync(input_file_path, 'utf8');
    const newFormat = file
      .replace("{", "[{")
      .replace(/}$/, "}]")

    console.log(JSON.parse('[' + newFormat + ']'));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接