Search code examples
javascriptpythonjsonjavascript-objectspython-jsonschema

How to create JSON objects Folder name and File Name View


I have a JSON File Like this:

{
    "Sheet1": [
        {
            "Folder name": "Folder 1",
            "Filename": "1- Introduction.mp4",
        },
        {
            "Filename": "2- Prerequisites.mp4",
        },
        {
            "Filename": "4- What is React Native.mp4",
        },
        {
            "Folder name": "Folder 2",
            "Filename": "1- Knowledge.mp4",
        },
        {
            "Filename": "2- Exercise.mp4",
        },]
 }

How Do I make it like this:

{
  "Folder 1": [
           {
            "Filename": "1- Introduction.mp4",
           },
           {
            "Filename": "2- Prerequisites.mp4",
           }
           ],

  "Folder 2": [
           {
            "Filename": "1- Knowledge.mp4",
           },
           {
            "Filename": "2- Exercise.mp4",
           }
           ]
}

I have New to JSON but I do Know Python Dictionaries. I Tried to do in Python but unable to do this exact way. Any help would be appreciated.


Solution

  • As pointed out by Taplar, you cannot create object values without keys in JSON. You can use an Array of objects instead.

    I'm considering that the folder will always be defined in the first element of the array and the next objects with just a "Filename" key will be inside the previous defined folder. Then, when another folder is found, the next files will be inside the new folder.

    With that in mind, you can use this function:

    const fs = require('fs');
    
    function mapFolderStructure(json) {
        const object = JSON.parse(json);
        const returnObject = {};
        let currentFolder = null;
        
        for (const key in object) {
            returnObject[key] = {};
            for (const item of object[key]) {
                if (item.hasOwnProperty('Folder name')) {
                    currentFolder = item['Folder name'];
                }
                
                if (currentFolder) {
                    if (!returnObject[key][currentFolder]) returnObject[key][currentFolder] = [];
                    returnObject[key][currentFolder].push({ Filename: item.Filename });
                }
            }
        }
    
        return JSON.stringify(returnObject, null, 4);
    }
    
    const inputJson = fs.readFileSync('path/to/input', 'utf8');
    
    const outputJson = mapFolderStructure(inputJson);
    
    fs.writeFileSync('path/to/output', outputJson);