简体   繁体   English

我有一个对象的 .log 文件,如何将它们转换为 JSON 对象以便在 Javascript 中进行迭代?

[英]I have a .log file of objects how do I convert them to a JSON object for iterating through in Javascript?

Here is a sample of the .log file I need to convert.这是我需要转换的 .log 文件的示例。 I am using Node.我正在使用节点。

    {"test": "data", "test1": 123, "foo": "feel me??"}
    {"test": "data", "test1": 123, "foo": "feel me??"}
    {"test": "data", "test1": 123, "foo": "feel me??"}

I am importing it by using this code.我正在使用此代码导入它。

let data = fs.readFileSync(log_path, 'utf8', function(err, data){
  if (err) throw err;
  let tweets = data.split('\n').map(line => JSON.parse(line));

  return tweets;

  fs.close(data, (err) => {
    console.log(err);
  })
})

As you can see it's not separated by commas so is not in JSON format.如您所见,它没有用逗号分隔,因此不是 JSON 格式。 I am trying to read the file, then split it by a new line, but that doesn't seem to be working.我正在尝试读取文件,然后用新行拆分它,但这似乎不起作用。

Assuming "feel me??"假设"feel me??" is meant to be a property, you could split up the lines and then map them to an array of objects:是一个属性,您可以split行,然后map它们map到对象数组:

 const text = ` {"test": "data", "test1": 123, "foo": "feel me??"} {"test": "data", "test1": 123, "foo": "feel me??"} {"test": "data", "test1": 123, "foo": "feel me??"}`; const arrOfObjs = text.split('\\n') .map(line => JSON.parse(line)); console.log(arrOfObjs);

The other problem is that readFileSync , as its name implies, reads the file synchronously .另一个问题是readFileSync ,顾名思义,是同步读取文件。 It doesn't accept a callback like that.它不接受这样的回调。 Change your file-reading code to:将您的文件读取代码更改为:

let data = fs.readFileSync(log_path, 'utf8');
// do stuff with the `data` string

Remember that since you're not working with a stream, you don't need fs.close .请记住,由于您不使用流, 因此不需要fs.close

Personally I used the read-last-lines package to get only a few last lines of my log file.我个人使用read-last-lines包来获取log文件的最后几行。

To make it work I had to slightly modify the code from the accepted answer, which was a great help for myself.为了使它工作,我不得不从接受的答案中稍微修改代码,这对我自己有很大帮助。 I am going to add it here in case if someone was struggling with a similar issue.如果有人遇到类似问题,我将在此处添加它。

readLastLines.read('info.log', 10)
      .then((lines) => {
        const arrOfStringObjs = lines.split('\n')
        let arrOfObjs = []
        arrOfStringObjs.forEach(strObj => {
          if (strObj !== undefined && strObj !== null && strObj !== '') {
            arrOfObjs.push(JSON.parse(strObj))
          }
        });
        console.log(arrOfObjs)

Hope it helps.希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM