.log文件读取并转换为json

时间:2018-04-09 09:55:33

标签: javascript json

我有.log文件,我需要在javascript中获取此文件并转换为JSON。我试试这个

var j= readTextFile("log991/sensorData.log");
        console.log(j);
        var jsonnn = JSON.stringify(j);  
        console.log(jsonnn);

但我只在控制台日志中获取路径。有没有办法做到这一点?

这就是.log文件的外观

2018-04-03 15:47:58,873 INFO log(17) batteryCurrent=-0.45, solarCurrent=3.27, 
hybridCurrent=0, batteryVoltage=12.88, solarVoltage=13.09
2018-04-03 15:48:00,074 INFO log(17) batteryCurrent=-0.45, solarCurrent=3.27, 
hybridCurrent=0, batteryVoltage=12.88, solarVoltage=13.09
2018-04-03 15:48:01,274 INFO log(17) batteryCurrent=-0.4, solarCurrent=3.28, 
hybridCurrent=0, batteryVoltage=12.89, solarVoltage=13.1

日Thnx

4 个答案:

答案 0 :(得分:2)

尝试此代码使用同步版

const fs = require('fs');
var text = fs.readFileSync('/somepath/a.txt','utf8')
console.log (text)

尝试将此代码转换为json

const fs = require('fs');
var text = fs.readFileSync('/somepath/a.txt','utf8')
array = text.split("\n")
var dataArray = [];
for(var i=0; i<array.length; i++){
  if(array[i] == ''){continue}
  let tempArray = []
  tempArray = array[i].split(",");
  dataArray.push(tempArray)
};

json = {};
var c = 1;
dataArray.forEach( (e1) =>{
  isdate = true;
  var tempjson = {};
  e1.forEach( (e2) =>{
    var key;
    if(isdate )  {
        key = 'date';
        tempjson[key] = e2;
        isdate = false;
    }
    else if(e2.includes("batteryCurrent")){
        key = "batteryCurrent";
        tempjson[key]= e2.split("batteryCurrent=")[1]
    }
    else{
        var arr = e2.split("=");
        key  = arr[0].trim();
        tempjson[key] = arr[1];
    }
  })
  json[c] = tempjson;
  c++
});

console.log(json)

答案 1 :(得分:1)

您使用的是节点吗?

const fs = require('fs')

fs.readFile('log991/sensorData.log', 'utf8', (err, data) => {
  console.log(data)
}

答案 2 :(得分:1)

使用readFile模块的fs方法。

var fs = require('fs')

fs.readFile('log991/sensorData.log', 'utf8', function(err, data) {

  console.log(data)
});

答案 3 :(得分:0)

好的,我用python修复此问题

import json 
a = open('log991/sensorData.log','r')
text = a.read()
text_as_list = text.split('\n')
keys = text_as_list[2].split()
result = []
for item in text.split('\n')[4:len(text_as_list)]:
temp_dict = {}  
for i,j in zip(keys,item.split()):  
    if j.isdigit():         
        temp_dict[i] = int(j)
    else:
        temp_dict[i] = j
result.append(temp_dict)
print (json.dumps(result))
相关问题