Nodejs将文本转换为JSON [英] Nodejs Convert text to JSON

查看:1300
本文介绍了Nodejs将文本转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,我很难将此txt文件转换为实际的javascript数组。

For some reason I'm having such a hard time converting this txt file to an actual javascript array.

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"}

目前我所拥有的不起作用

Currently what I have that doesn't work

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');


推荐答案

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

Since your file contains a JSON object per line, you could read that file line by line, using readline.

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

Each line is then parsed, and push into an array, which is then returned (resolved) after the file is fully read.

'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));

这篇关于Nodejs将文本转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆