recursive JSON.stringify implementation

后端 未结 6 1891
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 21:25

I am trying to learn recursion in Javascript, so I figured I\'d rewrite the native JSON.stringify function using recursion as a challenge to myself. I almost got my

6条回答
  •  没有蜡笔的小新
    2021-02-04 21:56

    I was asked this in an Interview question and this is what I came up with. An understandable recursive approach:

    ​
    function stringify(input) {
      var arrVals = [];
      Object.keys(input).forEach(function(keyName) {
        let val = input[keyName];
        if (typeof val !== 'undefined' && typeof val !== 'function') {
          arrVals.push(getQuotedString(keyName) + ":" + getString(val));
        }
      });
      return '{' + arrVals.join(',') + '}';
    }
    
    function getString(val) {
      switch (typeof val) {
        case 'string':
          return getQuotedString(val);
          break;
        
        case 'number':
        case 'boolean':
          return val;
          break;
        
        case 'object':
          if (val === null) {
            return "null";
          }
          
          if (Array.isArray(val)) {
            let arrString = []
            for (let i = 0; i < val.length; i++) {
              arrString.push(getString(val[i]));
            }
            return "[" + arrString.join(',') + "]";
          }
          
          return stringify(val);
          break;
      }
    }
    
    function getQuotedString(str) {
      return '"' + str + '"';
    }

    Test using following obj:

    ​
    var input = {
      "a": 1,
      "b": 'text',
      "c": {
        "x": 1,
        "y": {
          "x": 2
        }
      },
      "d": false,
      "e": null,
      "f": undefined,
      "g": [1, "text", {
        a: 1,
        b: 2
      }, null]
    };

提交回复
热议问题