Link to home
Start Free TrialLog in
Avatar of rito1
rito1

asked on

Replace colon characters in JSON fields

Hi All,

I would like to remove colons within JSON fields (properties) only and not the value parts.

Here is an example code:

var myJSON = {
  "path:t": "xlsx-file/xlsx_xml",
  "name:r": "xlsx_xml",
  "type:e": "folder"
}

Open in new window


Please could you provide me with the regexp pattern to use within a Javascript .replace() method which will identify colons (:) from within the property part only.

e.g. JSON.stringify(myJSON).toString(/regexp_pattern/g, '');

Thanks,

RIt
Avatar of leakim971
leakim971
Flag of Guadeloupe image

why do you think it's possible to do with a unique regex?
http://jsfiddle.net/7pL81wth/1/
var myJSON = {
  "path:t": "xlsx-file/xlsx_xml",
  "name:r": "xlsx_xml",
  "type:e": "folder"
}
var keys = [];
for(var key in myJSON) keys[keys.length] = key;
var mystring = keys.toString();
// checking
alert(mystring);

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Robert Schutt
Robert Schutt
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi,

You may create your own function that would iterate through the object's properties and create a new object:

var myJSON = {
  "path:t": "xlsx-file/xlsx_xml",
  "name:r": "xlsx_xml",
  "type:e": "folder"
}

var myStringify = function(obj){
  var result = {};
  for (var property in obj) {
      result[property.replace(/:/g, '')] = obj[property];
  }
  return JSON.stringify(result);
}

console.log(myStringify(myJSON));

Open in new window


This example is very simplistic meaning it only gets first level properties, but it could be a start.

A slightly modified version that would use recursion would be :

var myStringify = function(obj){
  var result = {};
  for (var property in obj) {
    if(typeof obj[property] === 'object'){
      obj[property] = myStringify(obj[property])
    }
    result[property.replace(/:/g, '')] = obj[property];
  }
  return result;
}
console.log(JSON.stringify(myJSON));
console.log(JSON.stringify(myStringify(myJSON)));

Open in new window


Still this is not perfect, as it doesn't take under consideration arrays.

Giannis
Avatar of rito1
rito1

ASKER

Excellent this works well. Thank you.
1) My solution is more than two time faster than the accepted answer
2) Using a function as callback ? could you say it's still a regex way? No, because at this point, you don't really care about the regex itself...