If you're parsing the JSON string, you can also use the reviver parameter of JSON.parse(string, [reviver])
:
var jsonStr = '{"Cat":"laps milk","Dog":"Woofs at Postman","Bird":"Jumps over the river","I":"Want to learn Regexp"}';
var result = JSON.parse(jsonStr, function (key, value) {
return value.replace(/ /g, " ");
});
Likewise, the stringify
method allows a replacer function which will replace any values when converting to a JSON string:
var obj = {"Cat":"laps milk","Dog":"Woofs at Postman","Bird":"Jumps over the river","I":"Want to learn Regexp"};
var result = JSON.stringify(obj, function (key, value) {
return value.replace(/ /g, " ");
});
Of course, this is assuming you're using json2.js or a browser with the correct ECMAScript 5th Edition implementation of the JSON object.