Skip to content

Instantly share code, notes, and snippets.

@syed-ahmad
Created October 25, 2023 12:24
Show Gist options
  • Save syed-ahmad/145d9d3b2df0dead1a3e101e138fbc48 to your computer and use it in GitHub Desktop.
Save syed-ahmad/145d9d3b2df0dead1a3e101e138fbc48 to your computer and use it in GitHub Desktop.
Clean JSON
const https = require('https');
https.get('https://coderbyte.com/api/challenges/json/json-cleaning', (resp) => {
let raw = '';
const expected = {"name":{"first":"Daniel","last":"Smith"},"age":45, "items_removed": 1};
// parse json data here...
let index = 1;
resp.on('data' , (chunk) => {
raw += chunk;
// process.stdout.write(chunk);
});
resp.on('end' , () => {
const parsed = JSON.parse(raw);
console.log(`🚀 parsed`, JSON.stringify(parsed, null, 2));
let items_removed = 0;
let removedItems = [];
const invalidStrings = ['N/A', '-', ''];
// Remove all keys that have values of N/A, -, or empty strings
Object.entries(parsed).forEach(([key, value]) => {
// string
if(typeof value == 'string' && invalidStrings.includes(value)) {
items_removed+=1;
console.log(`✅`, {key, value});
removedItems.push({[key]: value})
delete parsed[key]
};
// Object
if(isObjectLiteral(value)) {
// Get keys with invlaid values
Object.entries(value).forEach(([oKey, oValue]) => {
if(typeof oValue == 'string' && invalidStrings.includes(oValue)) {
console.log(`🚀`, {oKey, oValue});
removedItems.push({[oKey]: oValue});
items_removed+=1;
// delete parsed[key][oKey];
}
});
}
});
console.log(`items_removed`, items_removed)
console.log(`❌ removedItems`, JSON.stringify(removedItems, null, 2))
console.log(`-----`)
console.log(JSON.stringify(parsed, null, 2))
// If one of these values appear in an array, remove that single item from the array
// For all keys removed, create a key/value pair at the end of the
// output object with the key items_removed and the value is the count
});
// console.log(expected)
});
function isObjectLiteral (obj) {
return Object.prototype.toString(obj) == '[object Object]';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment