我有一个文本文件,其中每行用冒号分隔为4个类别,我想将其放入JSON文件中,其中每个类别都是JSON文件中对应名称的值。
示例data.txt
文件:
Date1:cat1:dog1:bug1
Date2:cat2:dog2:bug2
Date3:cat3:dog3:bug3
示例JSON文件:
{
"Date1": {
"cat": "cat1",
"dog": "dog1",
"bug": "bug1"
},
"Date2": {
"cat": "cat2",
"dog": "dog2",
"bug": "bug2"
...
...
}
我以前从未使用过JSON,但我认为这是格式化它的方式。我该如何使用冒号作为下一个值的标记对每一行进行排序,并使用JavaScript和Node.js以正确的名称将其存储在JSON文件中?
答案 0 :(得分:2)
如果您不想自己处理csv文件,请使用csv软件包。
const fs = require("fs");
const csv = require("csv");
const result = {};
const keys = ["cat", "dog", "bug"]
// Read data
const readStream = fs.createReadStream("yourfile.txt");
// Parser
const parser = csv.parse({ delimiter: ":" });
parser.on("data", (chunk) => {
result[chunk[0]] = {};
for(let i = 1; i < chunk.length; i ++) {
result[chunk[0]][keys[i - 1]] = chunk[i];
}
});
parser.on("end", () => {
console.log(result);
});
readStream.pipe(parser);
答案 1 :(得分:1)
如果您的JSON具有定义的结构,则可以使用以下代码进行处理:
import * as fs from 'fs';
/* If you have a large file this is a bad Idea, refer to reading from a stream
* From zhangjinzhou's answer
*/
const file = fs.readFileSync('path/to/data.txt', 'utf8');
const json = file.split(/\n|\r\n/).map(line => {
const values = line.split(":");
let obj = {}
obj[values[0]] = {
cat: values[1],
dog: values[2],
bug: values[3],
};
return obj
}).reduce((acc, current) => Object.assign(acc, current), {})
答案 2 :(得分:1)
使用RegExp和Array#forEach,将字符串转换为行,然后对其进行迭代,并通过以下方式用相应的数据填充super_market_prices=np.array([['Bread',5],['Loaf',100],['Meat_Chicken',2.4],['Meat_Cow',450]]).ravel()
item=str(input('Enter item name: '))
Final_item=item.title()
try:
index = np.where(super_market_prices == Final_item)[0]
print (float(super_market_prices[index+1][0]))
except ValueError:
print('Item not in list.')
:
object
然后使用JSON.stringify将const dataFileContent =
`Date1:cat1:dog1:bug1
Date2:cat2:dog2:bug2
Date3:cat3:dog3:bug3`;
function processData(data) {
// convert to lines
const lines = data.match(/[^\r\n]+/g) || [];
const object = {};
// iterate over the lines
lines.forEach(line => {
const parts = line.split(':');
const main = parts.shift();
const pattern = /^(.*?)(\d+)$/;
// create an object for each main part
object[main] = {};
// fill each main part with the sub parts
parts.forEach(part => {
const match = part.match(pattern) || [];
const key = match[1];
const value = match[2];
if (match) {
object[main][key] = key + value;
}
});
});
return object;
}
const processedData = processData(dataFileContent);
console.log(processedData);
转换为JSON并通过以下方式将其保存到文件中:
processedData
对于较大的文件,请考虑按照Streams的建议在Node.js中使用@zhangjinzhou。