简体   繁体   中英

How to convert text file into an array of objects?

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 .

customerArr.map(i => JSON.parse(i));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM