[英]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 .您正在使用的格式称为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
将其映射到对象。
customerArr.map(i => JSON.parse(i));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.