Skip to content

Instantly share code, notes, and snippets.

@danielsan
Created May 17, 2020 18:31
Show Gist options
  • Save danielsan/235959b92c7b6425dc6d94f154a3c654 to your computer and use it in GitHub Desktop.
Save danielsan/235959b92c7b6425dc6d94f154a3c654 to your computer and use it in GitHub Desktop.
Answer to stackoverflow 61825263

This gist is to support the answer to this Stackoverflow 61825263 question

https://stackoverflow.com/questions/61825263/how-to-format-the-file-containing-json-objects-to-json-array

run it as the following code

node log-parser.js logfile.log

What you'll see on your screen is this:

[
  { Name: 'nom1', Cities: [ 'city1', 'city2' ] },
  { Name: 'nom2', Cities: [ 'city4', 'city5' ] },
  { Name: 'nom3', Cities: [ 'city3', 'city6' ] },
  { Name: 'nom4', Cities: [ 'city7', 'city8' ] },
  { Name: 'nom5', Cities: [ 'city9', 'cityA' ] },
  { Name: 'nom6', Cities: [ 'cityB', 'cityC' ] }
]
const fs = require('fs')
async function fileToArray (file) {
const fileContent = await fs.promises.readFile(file)
const singleLined = fileContent
.toString()
.replace(/\n/g, '')
.replace(/\}\{/g, '},{')
.replace(/(\w+):/g, '"$1":')
.replace(/'/g, '"')
const array = JSON.parse(`[${singleLined}]`)
console.log(array)
}
fileToArray(process.argv[2])
{
Name:"nom1",
Cities:['city1','city2']
}
{
Name:"nom2",
Cities:['city4','city5']
}
{
Name:"nom3",
Cities:['city3','city6']
}
{
Name:"nom4",
Cities:['city7','city8']
}
{
Name:"nom5",
Cities:['city9','cityA']
}
{
Name:"nom6",
Cities:['cityB','cityC']
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment