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?
-
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]?
-
Once tested, how to take the
payload
key/values and munge/update them back into thesource.json`` file? I am guessing
JSON.stringify(array) => fs.write(target)“` or something similar?
Thanks everyone!