Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim white spaces in both Object key and value recursively

How do you trim white spaces in both the keys and values in a JavaScript Object recursively?

I came across one issue in which I was trying to "clean" a user supplied JSON string and send it into my other code for further processing.

Let's say we've got a user supplied JSON string whose property key and value are of type "string". However, what's problematic in this case is that the keys and values are not as clean as desired. Say a { " key_with_leading_n_trailing_spaces ": " my_value_with_leading_spaces" }.

In this case, it can easily cause issue with your brilliantly written JavaScript program trying to make use of such data(or should we call it dirty data?) because when your code is trying to get the value out of this JSON object, not only the key is not matching but also the value can not be matched. I have looked around google and found a few tips but there is not one cure that cure it all.

Given this JSON with lots of white spaces in keys and values.

var badJson = {
  "  some-key   ": "    let it go    ",
  "  mypuppy     ": "    donrio   ",
  "   age  ": "   12.3",
  "  children      ": [
    { 
      "   color": " yellow",
      "name    ": "    alice"
    },    { 
      "   color": " silver        ",
      "name    ": "    bruce"
    },    { 
      "   color": " brown       ",
      "     name    ": "    francis"
    },    { 
      "   color": " red",
      "      name    ": "    york"
    },

  ],
  "     house": [
    {
      "   name": "    mylovelyhouse     ",
      " address      " : { "number" : 2343, "road    "  : "   boardway", "city      " : "   Lexiton   "}
    }
  ]

};

So this is what I came up with ( with help of using lodash.js):

//I made this function to "recursively" hunt down keys that may 
//contain leading and trailing white spaces
function trimKeys(targetObj) {

  _.forEach(targetObj, function(value, key) {

      if(_.isString(key)){
        var newKey = key.trim();
        if (newKey !== key) {
            targetObj[newKey] = value;
            delete targetObj[key];
        }

        if(_.isArray(targetObj[newKey]) || _.isObject(targetObj[newKey])){
            trimKeys(targetObj[newKey]);
        }
      }else{

        if(_.isArray(targetObj[key]) || _.isObject(targetObj[key])){
            trimKeys(targetObj[key]);
        }
      }
   });

}

//I stringify this is just to show it in a bad state
var badJson = JSON.stringify(badJson);

console.log(badJson);

//now it is partially fixed with value of string type trimed
badJson = JSON.parse(badJson,function(key,value){
    if(typeof value === 'string'){
        return value.trim();
    }
    return value;
});

trimKeys(badJson);

console.log(JSON.stringify(badJson));

Note here : I did this in a 1, 2 steps because I could not find a better one shot to deal it all solution. If there is issue in my code or anything better, please do share with us.

Thanks!

like image 492
vichsu Avatar asked Nov 03 '15 22:11

vichsu


People also ask

Does json Stringify remove white spaces?

Calling JSON. stringify(data) returns a JSON string of the given data. This JSON string doesn't include any spaces or line breaks by default.

How to remove whitespace from object in JavaScript?

trim() The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.)

How do I remove all spaces from a json file?

Remove all the spaces, newline or tab present in the key using replace() function and add underscore "_" between the word of the key instead of whitespace.

What is a json encoded string?

The method JSON. stringify(student) takes the object and converts it into a string. The resulting json string is called a JSON-encoded or serialized or stringified or marshalled object.


1 Answers

You can just stringify it, string replace, and reparse it

JSON.parse(JSON.stringify(badJson).replace(/"\s+|\s+"/g,'"'))
like image 127
epascarello Avatar answered Sep 18 '22 12:09

epascarello