0

I have .log file and I need to get this file in javascript and convert to JSON. I try this

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

But I only get path in console log. Is there any way to make this?

this is how .log file looks

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

Arter
  • 2,224
  • 3
  • 29
  • 66

4 Answers4

2

Are you using node?

const fs = require('fs')

fs.readFile('log991/sensorData.log', 'utf8', (err, data) => {
  console.log(data)
}
Glutch
  • 662
  • 1
  • 6
  • 19
2

try this code used synchronous version

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

try this code to convert into 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)
ashwintastic
  • 2,262
  • 3
  • 22
  • 49
1

Use the readFile method of fs module.

var fs = require('fs')

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

  console.log(data)
});
Charlie
  • 22,886
  • 11
  • 59
  • 90
0

Ok, i fix this with 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))
Arter
  • 2,224
  • 3
  • 29
  • 66