使用节点js动态构建JSON

时间:2018-10-25 03:56:39

标签: javascript node.js json

我在一个特定的文件夹中有(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 */


  });
}

感谢任何帮助/指导。

2 个答案:

答案 0 :(得分:1)

除了您现有的代码外,我还添加了用于构造所需输出的逻辑。

function buildJSON() {
    // empty result
    let result = { label: {}, sample: {}};

    fs.readdirSync('/path/to/file/').forEach(file => {
        const file_path = '/path/to/file/' + file;
        const data = fs.readFileSync(file_path);
        const items = JSON.parse(data);

        // remove .json extension, this will be used to construct labels
        const file_name = file.replace(/\..+$/, "");

        // loop through each item in the json file
        for(let item of items) {
            // construct labels
            result.label[item.label] = { isA : file_name }

            // construct samples
            result.sample[item.sample.join("|")] = item.label;
        }
    });

    return result;
}

答案 1 :(得分:0)

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

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);