0

I have a json object that has encrypted values, I'll simplify this and pretend all values are numbers and i need the number x3 for this question. Is there a way to loop through the json object and update every value then return a decrypted version of the original object:

var encrypted = {
         a: 10,
         b: 4,
         c: {x:3, y:2, z:1},
 }

var decrypted = decryptJSON(encrypted) //<--- looking for this function


//decrypted = {
//         a: 30,
//         b: 12,
//         c: {x:9, y:6, z:3},
// }

I've tried looping through the object using something like https://stackoverflow.com/a/29516227/620723 but this would only really work for a non nested json object.

Also the example I gave above is only nested one level in reality i may have nests inside nests inside nest inside....

Woodsy
  • 3,177
  • 2
  • 26
  • 50
  • If you are able to first use `JSON.parse(encrypted)`, then you should be able to just decrypt whatever key nested in your JSON, no? e.g.: `let encryptedParsed =JSON.parse(encrypted) decryptJSON(encryptedParsed.c.x)` – Niss Dec 05 '17 at 17:42
  • So i would first need to get every key value first? do something like getKeys and return [a, b, c.x, c.y, c.z] right? – Woodsy Dec 05 '17 at 17:46
  • Yeah... I assumed you wanted to decrypt one particular value there but your question is more complex and you may have to use some for...in loops. – Niss Dec 05 '17 at 17:55
  • yes one value is straight forward but I was looking decrypting every value in a json object which i don't know the schema for. – Woodsy Dec 05 '17 at 18:09

1 Answers1

2

You could write a recursive function to traverse the object and update your values. Here is a quick example:

var encrypted = {
    a: 10,
    b: 4,
    c: {x: 3, y: 2, z: 1},
};

var updateObject = function (obj) {
    for (var key in obj) {
        obj[key] = updateValue(obj[key]);
    }
    return obj;
}

var updateValue = function(value) {
    if (typeof(value) === "object") {
        return updateObject(value);
    } else {
        return value * 3;
    }
}

updateObject(encrypted);
console.log(encrypted);

Please note that this will only work as long as you only have objects and numeric values in your object. You will definitely need to adjust the functions if your data is more dynamic.

This should get you started though!

Ezeke
  • 952
  • 7
  • 19
  • Thanks, Yes I know this will work with numbers but that's okay. I will just need to replace the return value * 3 with the return decrypt(value) I should have a working decrypter. Thanks again – Woodsy Dec 05 '17 at 17:59