Arter
Arter

Reputation: 2324

.log file read and convert to json

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

Upvotes: 0

Views: 2844

Answers (4)

ashwintastic
ashwintastic

Reputation: 2312

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)

Upvotes: 2

Arter
Arter

Reputation: 2324

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

Upvotes: 0

Glutch
Glutch

Reputation: 720

Are you using node?

const fs = require('fs')

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

Upvotes: 2

Charlie
Charlie

Reputation: 23838

Use the readFile method of fs module.

var fs = require('fs')

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

  console.log(data)
});

Upvotes: 1

Related Questions