Home > Back-end >  Testing JSON key and then writing nested values to existing JSON file
Testing JSON key and then writing nested values to existing JSON file

Time:04-19

I have a changes.json file which has directives as key value pairs i.e. "action": "add" that I wish to test and depending on that test to then read in the payload to an array and update a source.json file. First here is the format of the original source JSON file. There are three sections to test, users, playlists, and songs.

{
    "users" : [
      {
        "id" : "1",
        "name" : "Albin Jaye"
      }
    ],
    "playlists" : [
      {
        "id" : "1",
        "owner_id" : "2",
        "song_ids" : [
          "8",
          "32"
        ]
      }
    ],
    "songs": [
      {
        "id" : "1",
        "artist": "Camila Cabello",
        "title": "Never Be the Same"
      }
    ]
  }

And then the changes.json file that has the action directive to tell the code how to process, i.e. update, delete, add, etc

{
    "users": [{
        "action": "add",
        "payload": [{
                "id": "1",
                "name": "Albin Jaye"
            },
            {
                "id": "2",
                "name": "Dave Mustaine"
            }
        ]
    }],
    "playlist": [{
        "action": "add",
        "payload": [{
            "id": "1",
            "owner_id": "2",
            "song_ids": [
                "8",
                "32"
            ]
        }]
    }],
    "songs": [{
        "action": "add",
        "payload": [{
            "id": "1",
            "artist": "Camila Cabello",
            "title": "Never Be the Same"
        }]
    }]
}

Here is the code I have so far. First section I am able to iterate over the JSON and test the key by a switch:

Object.entries(data).map(([key, [{ action, payload }]]) => { 
    console.log(key, [{action, payload}]);
                    
    switch (key) {
        case 'users':
        // How to test for "add":"action"???
        // How to read in nested "payload"
        // How to update source JSON file with this value?
        break;
                        
    }
});

And for one of the tests/part, I have this code that reads through key/value pairs and pushes to array, but not sure about a couple of things.

const array = [];

    for (const [key, value] of Object.entries(data)) {
        if (data[key] === 'payload') {
            array.push([`${key}`, `${value}`]);
        }
    }
    console.log(array)
    // after reading into array, how to update source.json file with new data?
  1. How to test for the "action":"add" key/value once I test for "user" node. This is probably just a syntax thing? data[user.action]?

  2. Once tested, how to take the payload key/values and munge/update them back into the source.json`` file? I am guessing JSON.stringify(array) => fs.write(target)``` or something similar?

*ASIDE: I understand there might be a simple way to do the test and add to the source JSON without reading into arrays like I am doing. Maybe something with fs.append() and JSON.parse?

CodePudding user response:

The snippet below checks whether the action is add:

let data = {
    users: [{
        action: "add",
        payload: [{
                id: "1",
                name: "Albin Jaye"
            },
            {
                id: "2",
                name: "Dave Mustaine"
            }
        ]
    }],
    playlist: [{
        action: "add",
        payload: [{
            id: "1",
            owner_id: "2",
            song_ids: [
                "8",
                "32"
            ]
        }]
    }],
    songs: [{
        action: "add",
        payload: [{
            id: "1",
            artist: "Camila Cabello",
            title: "Never Be the Same"
        }]
    }]
}

Object.entries(data).map(([key, [{ action, payload }]]) => { 
    //console.log(key, [{action, payload}]);
                    
    switch (key) {
        case 'users': {
            if (action === "add") console.log("it's an add");
            else console.log("it's not an add");
        }
        break;
                        
    }
});

As about updating your JSON, kindly read How to update a value in a json file and save it through node.js for more information.

CodePudding user response:

This might helps you.

const data = {
    "users": [
        {
            "id": "1",
            "name": "Albin Jaye"
        }
    ],
    "playlists": [
        {
            "id": "1",
            "owner_id": "2",
            "song_ids": [
                "8",
                "32"
            ]
        }
    ],
    "songs": [
        {
            "id": "1",
            "artist": "Camila Cabello",
            "title": "Never Be the Same"
        }
    ]
};

const keys = Object.keys(data);

for (let i = 0; i < keys.length; i  ) {
    switch (keys[i]) {
        case 'users':
            data[keys[i]] = [
                {
                    action: 'add',
                    payload: data[keys[i]],
                }
            ];
            break;
        case 'songs':
            data[keys[i]] = [
                {
                    action: 'add',
                    payload: data[keys[i]],
                }
            ];
            break;
        case 'playlists':
            data[keys[i]] = [
                {
                    action: 'add',
                    payload: data[keys[i]],
                }
            ];
            break;
    }
}

console.log(data);
  • Related