0

I have a JSON file format as follows:

[{"key/1":"Value1", "key/2":"Value2" },
{"key/1.1":"Value1.1", "key/2.1":"Value2.1" },
{"key/1.2":"Value1.2", "key/2.2":"Value2.2" },
{"key/1.3":"Value1.3", "key/2.3":"Value2.3" }]

My requirement is to search all exixting key names in above JSON format and repalce the slash("/") character to some othere character to have the new JSON file with changed Key names with new replaced character.

Please help

Thanks

manjul
  • 11
  • 1

2 Answers2

0

Using this function, you can clone the object. Just modify it a little to replace key slashes on the fly.

Open your console and run it

function replaceSlashInKeys(obj) {
    if(obj == null || typeof(obj) != 'object') return obj;
    
    var temp = obj.constructor();
    
    for(var key in obj) {
        if(obj.hasOwnProperty(key)) {
            // Replace any slash with an underscore (in the key)
            temp[key.replace(/\//g, '_')] = replaceSlashInKeys(obj[key]);
        }
    }
    return temp;
}

// Example usage

var test = [{"key/1":"Value1", "key/2":"Value2" },{"key/1.1":"Value1.1", "key/2.1":"Value2.1" },{"key/1.2":"Value1.2", "key/2.2":"Value2.2" },{"key/1.3":"Value1.3", "key/2.3":"Value2.3" }];

// Got slashes
console.log(test);
// Replace them
test = replaceSlashInKeys(test);
// Got underscores
console.log(test);
Community
  • 1
  • 1
blex
  • 24,941
  • 5
  • 39
  • 72
  • var temp = obj.constructor(); What is the meaning of this line of code. I am pretty new to Javascripts. Sorry for so basic questions. Please help me out. Thanks – manjul Mar 17 '15 at 13:37
  • @manjul Every type has a _constructor_ function, which will return an _instance_ of it. See [this JS fiddle](http://jsfiddle.net/yn6jwpgz/) which demonstrates this. If your object is an array, `temp` will be an array. If it is an object with properties, it will be an object. That's useful in this case, because it is a _recursive_ function (iterates over _nested objects_). To put it in a simple way: It just makes sure to keep the same object type as the one you give it as a parameter. Otherwise you might get unexpected results. – blex Mar 17 '15 at 13:47
0

Another approach using the reduce function could be:

for (var i = 0; i < test.length; i++){
    Object.keys(test[i]).reduce(function (a, b) {
        test[i][b.toString().replace('/', '-')] = test[i][b];
        delete test[i][b];
    }, 1);
}

jsfiddle:

https://jsfiddle.net/fwp7zj3k/

Ivan Sivak
  • 7,178
  • 3
  • 36
  • 42