gpt4 book ai didi

javascript - 使用 node js 动态构建 JSON

转载 作者:行者123 更新时间:2023-11-30 20:05:25 24 4
gpt4 key购买 nike

我在特定文件夹中有 (n) 个 JSON 文件:

为简单起见,假设有 3 个 JSON 文件 Animal.json、Noun.json、POS.JSON

它们的内容分别是

Animal.json

[
{
"label": "Dinosaur",
"sample": ["#Noun Rex","saurus"]
},
{
"label": "Lion",
"sample": ["simba"]
},
{
"label": "Tiger",
"sample": ["big cat"]
}
]

Noun.json

[
{
"label": "Animal",
"sample": ["Herbivore","Carnivore"]
}
]

POS.json

[
{
"label": "Noun",
"sample": ["Proper","Common"]
}
]

我希望能够遍历特定文件夹中的所有 JSON 文件并动态构建以下格式的 JSON

label: {
Dinosaur: {
isA: 'Animal'
},
Lion: {
isA: 'Animal'
},
Tiger: {
isA: 'Animal'
},
Animal: {
isA: 'Noun'
},
Noun: {
isA: 'POS'
}
},
sample: {
'#Noun rex|saurus': 'Dinosaur',
'simba': 'Lion'
'big cat': 'Tiger',
'Herbivore|Carnivore' : 'Animal',
'Proper|Common' : 'Noun'

}

到目前为止我的逻辑:

function buildJSON() {
fs.readdirSync('/path/to/file').forEach(file => {

const path = '/path/to/file' + file;
const data = fs.readFileSync(path);
const txt = JSON.parse(data);

console.log(JSON.stringify(txt)); //Displays content of each file

/* I need the logic to build the lable and sample for the output json */


});
}

感谢任何帮助/指导。

最佳答案

您可以简单地使用 Array.reduce() 来创建一个 map :

let animal =  [ { "label": "Dinosaur", "sample": ["#Noun Rex","saurus"] }, { "label": "Lion", "sample": ["simba"] }, { "label": "Tiger", "sample": ["big cat"] } ];
let noun = [ { "label": "Animal", "sample": ["Herbivore","Carnivore"] } ];
let pos =[ { "label": "Noun", "sample": ["Proper","Common"] } ];

function getResult(arr, isA, result){
result = arr.reduce((a, curr)=>{
a.label = a.label || {};
a.label[curr.label] = {
"isA" : isA
};
a.sample = a.sample || {};
a.sample[curr.sample.join("|")] = curr.label;
return a;
}, result);
return result;
}
let result= {};
getResult(animal, "Animal", result);
getResult(noun, "Noun", result);
getResult(pos, "Pos", result);
console.log(result);

关于javascript - 使用 node js 动态构建 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52981135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com