如何在JavaScript中读取文件并将其转换为JSON数组?

huangapple go评论63阅读模式
英文:

How to read a file and convert to json array in javascript?

问题

以下是翻译好的内容:

如果我有一个如下的文件:

key1 key2
data1 data2
data3 data4
...

是否有一种简单的方法来读取这个文件并将其转换成JSON对象数组?
我想要的最终输出是:

[{key1: data1, key2: data2}, {key1: data3, key2: data4}, ...]
英文:

If I have a file like below:

key1 key2
data1 data2
data3 data4
...

Is there an easy way to read this file and convert it to a json object array?
The final output I want is :

[{key1:data1, key2: data2},{key1: data3, key2: data4}, ...]

答案1

得分: 1

// 导入文件系统模块并读取文件,将其拆分为行和单元格
const data = fs.readFileSync('./text.txt').toString().split('\n').map(row => row.match(/\w+/g));
// 获取具有键名的第一行
const head = data.shift();

// 将其余行映射到具有来自第一行的键的对象中
const result = data.map(row => Object.fromEntries(row.map((cell, idx) => [head[idx], cell])));
console.log(JSON.stringify(result));

结果:

/usr/local/bin/node ./read-csv.mjs
[{"key1":"data1","key2":"data2"},{"key1":"data3","key2":"data4"}]

如果需要在处理大文件时提高速度,请使用 Array::reduce()

const data = fs.readFileSync('./text.txt').toString().split('\n').map(row => row.match(/\w+/g));
const head = data.shift();

const result = data.map(row => row.reduce((obj, cell, idx) => {
    obj[head[idx]] = cell;
    return obj;
}, {}));
console.log(JSON.stringify(result));

如果需要最大速度,请使用 for 循环:

const data = fs.readFileSync('./text.txt').toString().split('\n').map(row => row.match(/\w+/g));
const head = data.shift();

const result = [];

for (let i = 0; i < data.length; i++) {
    const row = data[i];
    const item = result[result.length] = {};
    for (let j = 0; j < row.length; j++) {
        item[head[j]] = row[j];
    }
}

console.log(JSON.stringify(result));

<details>
<summary>英文:</summary>

import fs from 'fs';

// read the file and split into rows and cells
const data = fs.readFileSync('./text.txt').toString().split('\n').map(row => row.match(/\w+/g));
// get the first row with cells as key names
const head = data.shift();

// map the rest of the rows into objects with keys from the first row
const result = data.map(row => Object.fromEntries(row.map((cell, idx) => [head[idx], cell])));
console.log(JSON.stringify(result));


The result:

/usr/local/bin/node ./read-csv.mjs
[{"key1":"data1","key2":"data2"},{"key1":"data3","key2":"data4"}]


If you need some speed boost with a big file, use `Array::reduce()`:

import fs from 'fs';

const data = fs.readFileSync('./text.txt').toString().split('\n').map(row => row.match(/\w+/g));
const head = data.shift();

const result = data.map(row => row.reduce((obj, cell, idx) => {
obj[head[idx]] = cell;
return obj;
}, {}));
console.log(JSON.stringify(result));


If you need the maximum speed use `for` loops:

import fs from 'fs';

const data = fs.readFileSync('./text.txt').toString().split('\n').map(row => row.match(/\w+/g));
const head = data.shift();

const result = [];

for (let i = 0; i < data.length; i++) {
const row = data[i];
const item = result[result.length] = {};
for (let j = 0; j < row.length; j++) {
item[head[j]] = row[j];
}
}

console.log(JSON.stringify(result));


</details>



# 答案2
**得分**: 0

你正在使用纯粹的JavaScript还是NodeJS?NodeJS拥有`fs`包,其中包含用于执行文件系统操作的实用函数。

无论您使用Node还是纯粹的JS,您都可以考虑以下方法。

```javascript
将文件读入一个变量(这里不包含代码,因为方法将根据您使用的是Node还是纯粹的JS而变化),称之为fileContent

let lines = fileContent.split("\n");

const result = [];

lines.forEach(line => {
  let dataValues = line.split(" "); //假设值以空格分隔
  result.push({key1: dataValues[0], key2: dataValues[1]});
});

result将保存所需的输出。

另一个可能对您有用的帖子

希望这对您有所帮助。

英文:

Are you using Vanilla Javascript or NodeJS? Node has the package fs which has got utility functions to perform filesystem operations.

Irrespective of whether you are using Node or Vanilla JS, you could consider the following approach.

Read the file into a variable(not adding the code for that here as the method will vary depending on whether you are using Node or Vanilla JS), say fileContent

let lines = fileContent.split(&quot;\n&quot;);

const result = [];

lines.forEach(line =&gt; {
  let dataValues = line.split(&quot; &quot;); //Assuming the values are separated by space
  result.push({key1: dataValues[0], key2: dataValues[1]});
});

result will hold the required output.

Another post that might be useful for you.

Hope this helps.

答案3

得分: -1

这段Python代码将为您完成此任务:

import json

def convert_file_to_json(filename):
    with open(filename, 'r') as file:
        lines = file.readlines()

    # 从第一行提取键
    keys = lines[0].split()

    # 创建JSON对象数组
    json_objects = []
    for line in lines[1:]:
        values = line.split()
        json_object = {keys[i]: values[i] for i in range(len(keys))}
        json_objects.append(json_object)

    return json.dumps(json_objects)

# 使用示例
filename = 'your_file.txt'
json_data = convert_file_to_json(filename)
print(json_data)

请注意,这是一个Python代码示例,用于将文本文件转换为JSON格式的数据。

英文:

This python code will do it for you

import json

def convert_file_to_json(filename):
    with open(filename, &#39;r&#39;) as file:
        lines = file.readlines()
    
    # Extract keys from the first line
    keys = lines[0].split()

    # Create JSON object array
    json_objects = []
    for line in lines[1:]:
        values = line.split()
        json_object = {keys[i]: values[i] for i in range(len(keys))}
        json_objects.append(json_object)

    return json.dumps(json_objects)

# Usage example
filename = &#39;your_file.txt&#39;
json_data = convert_file_to_json(filename)
print(json_data)

huangapple
  • 本文由 发表于 2023年7月10日 11:13:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76650476.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定