Home > Enterprise >  NodeJS Newline delimited strings to array of objects
NodeJS Newline delimited strings to array of objects

Time:10-20

How do I make a text file being read as:

`{'values': [0,1,0], 'key': 0}
{'values': [1,1,0], 'key': 1}
{'values': [1,1,0], 'key': 1}`

via:

  var fs = require('fs');
  fs.readFile("logfile.txt", 'utf8', function(err, data){

  console.log("DATA: ", data);
  return data
   });
  console.log('readFile called');

A list of dictionaries newline delimited into an array.

Wanted output:

[{'values': [0,1,0], 'key': 0},
    {'values': [1,1,0], 'key': 1},
    {'values': [1,1,0], 'key': 1}]

CodePudding user response:

const str = `{'values': [0,1,0], 'key': 0}
             {'values': [1,1,0], 'key': 1}
             {'values': [1,1,0], 'key': 1}`;

Seeing the structure of the string, you can parse it with a regex to extract the objects

const match = str.match(/({.*})/gm);

Then you have to correct the string to use double quote (JSON uses double quotes only) and parse each string

const result = match.map(objStr => {
  objStr = objStr.replace(/'/g, '"')
  return JSON.parse(objStr)
});
  • Related