Search code examples
javascriptjsonnode.jsreal-time

How to save data in json format?


I created a program that receives data from four channels. This is the type of data. ( 0.499147;0.499147;0.499147;0.499147; )
(Separated by ';') Data can be read every interval set up to 100 times. So I want to save the received data in JSON format. I wrote the following code but could not save it in JSON format.

port.on('data',function(devicevalue){
arrayvalue = devicevalue.toString();
eachvalue = arrayvalue.split(';');

ch0value = eachvalue[0];
ch1value = eachvalue[1];
ch2value = eachvalue[2];
ch3value = eachvalue[3];

var json_data = 
        {
        index : i ,
        ch0value : eachvalue[0],
        ch1value : eachvalue[1],
        ch2value : eachvalue[2],
        ch3value : eachvalue[3],
        };

Later if i write this code

   jsonfile.writeFile(file,json_data,{flag: 'a', spaces: 2},function(err){
        console.error(err)
   });

[https://i.sstatic.net/DMc5M.png][https://i.sstatic.net/DMc5M.png]

If i write this instead of the above

    var objjson = JSON.stringify(json_data);
    jsonfile.writeFile(file,objjson,{flag: 'a', spaces: 2},function(err){
    console.error(err)
    });

[ https://i.sstatic.net/8ldPG.png][https://i.sstatic.net/8ldPG.png]

If I want this form, how do I write the code?

[https://i.sstatic.net/nEr3e.png][https://i.sstatic.net/nEr3e.png]


Solution

  • How about this:

    var results = [];
    var i = 0;
    port.on('data', function(devicevalue) {
      var newElement = {
        index: i,
        ch0value: eachvalue[0],
        ch1value: eachvalue[1],
        ch2value: eachvalue[2],
        ch3value: eachvalue[3],
        ch4value: eachvalue[4]
      };
      results.push(newElement);
      i++;
    });
    
    port.on('close', function(code, signal) {
      jsonfile.writeFile(file,results,{flag: 'a', spaces: 2}, console.log);
    });