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:
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).toS tring(/reg exp_patter n/g, '');
Thanks,
RIt
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"
}
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).toS
Thanks,
RIt
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Hi,
You may create your own function that would iterate through the object's properties and create a new object:
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 :
Still this is not perfect, as it doesn't take under consideration arrays.
Giannis
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));
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)));
Still this is not perfect, as it doesn't take under consideration arrays.
Giannis
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...
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...
http://jsfiddle.net/7pL81wth/1/
Open in new window