How to convert text file into an array of objects?

Tags: , ,

I have a text which looks like the following

{"age": "52", "id": 1, "name": "Hulk"}
{"age": "33", "id": 2, "name": "Iron Man"}

I want to read the file and put it into an array of objects.

This is what I have done so far

const fs = require("fs");
const customerFile = fs.readFileSync("./customers.txt", "utf-8");
const customerArr = customerFile.split("n");

As you can see I am splitting the file, which creates an array but I am stuck on how to convert the items in the array into objects. How can I do this?


The format you’re working with is called ndjson. You could try looking for a parser made specifically for it.

Or if you’re reading it line by line into array, you can then map it to objects using JSON.parse. => JSON.parse(i));

Source: stackoverflow