Skip to content

Instantly share code, notes, and snippets.

@daguitosama
Created October 24, 2024 15:49
Show Gist options
  • Save daguitosama/e9df7b6daa635ac16cdd80993a7b0a51 to your computer and use it in GitHub Desktop.
Save daguitosama/e9df7b6daa635ac16cdd80993a7b0a51 to your computer and use it in GitHub Desktop.
Removes all the specified keys from a JSON file and prints the cleaned result back
const fs = require("fs");
const path = require("path");
/**
* Function to keep only specified keys in an object.
* @param {Object} obj - The object to filter.
* @param {Array<string>} keysToKeep - The keys to keep in the object.
* @returns {Object} - A new object with only the specified keys.
*/
function keepObjectKeys(obj, keysToKeep) {
const keptObj = {};
keysToKeep.forEach((key) => {
if (obj.hasOwnProperty(key)) {
keptObj[key] = obj[key]; // Keep the key if it exists
}
});
return keptObj;
}
/**
* Main function to read, filter, and output JSON.
* @param {string} filePath - The path to the JSON file.
* @param {Array<string>} keysToKeep - The keys to keep in each object.
*/
function keepKeys(filePath, keysToKeep) {
// Read the JSON file
fs.readFile(filePath, "utf8", (err, data) => {
if (err) {
console.error(`Error reading file: ${err.message}`);
process.exit(1);
}
try {
const jsonData = JSON.parse(data); // Parse the JSON data
// Check if jsonData is an array or an object
const filteredData = Array.isArray(jsonData)
? jsonData.map((item) => keepObjectKeys(item, keysToKeep))
: keepObjectKeys(jsonData, keysToKeep);
console.log(JSON.stringify(filteredData, null, 2)); // Output filtered JSON
} catch (parseError) {
console.error(`Error parsing JSON: ${parseError.message}`);
process.exit(1);
}
});
}
// Get command line arguments
const args = process.argv.slice(2);
if (args.length < 2) {
console.error("Usage: keepKeys <filename.json> <key1> [<key2> ...]");
process.exit(1);
}
const fileName = args[0];
const keysToKeep = args.slice(1);
// Resolve the full path of the file
const filePath = path.resolve(__dirname, fileName);
// Call the main function to keep specified keys
keepKeys(filePath, keysToKeep);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment