2

For an assignment, I'm trying to implement the JSON.stringify functionality recursively.

However, my current approach - which attempts to directly return a string concatenating the object's key/value pairs - doesn't work because the parenthesis and commas are misplaced. Ideally, I would be able to recursively construct an array and then join the elements with commas, but am unsure how to do this. Any suggestions or alternative approaches?

Thank you!

var stringifyJSON = function(obj) {
  if (typeof(obj) == "object") {
    var newValue;
    var objKeys = Object.keys(obj);
    if (Object.keys(obj).length === 0) {
      return "";
    }
    else if (Object.keys(obj).length !== 0) {
      var key = (typeof(objKeys[0]) == "string") ? '"' + objKeys[0] + '"' : objKeys[0];
      var value = (typeof(obj[objKeys[0]]) == "string") ? '"' + obj[objKeys[0]] + '"' : obj[objKeys[0]];
      newValue = key + ":" + value;
      delete obj[objKeys[0]];
    }
    return "{" + newValue + "," + stringifyJSON(obj) + "}";
  }
};
2
  • First implement a function that accepts only strings, numbers and booleans. Then adding support for arrays and objects will be much easier. Commented Aug 10, 2015 at 1:17
  • Great suggestion, thank you! Commented Sep 10, 2015 at 21:08

1 Answer 1

0

I have created the whole implementation of the JSON.stringify() method in a recursive way. You need to handle Arrays and Object differently and make recursive based on Data type. Especially for last commas, you can just pop it without any extra time cost that would help you not to worry about adding a comma at every recursive tree.


const JSONStringify = (obj) => {

  const isArray = (value) => {
    return Array.isArray(value) && typeof value === 'object';
  };

  const isObject = (value) => {
    return typeof value === 'object' && value !== null && !Array.isArray(value);
  };

  const isString = (value) => {
    return typeof value === 'string';
  };

  const isBoolean = (value) => {
    return typeof value === 'boolean';
  };

  const isNumber = (value) => {
    return typeof value === 'number';
  };

  const isNull = (value) => {
    return value === null && typeof value === 'object';
  };

  const isNotNumber = (value) => {
    return typeof value === 'number' && isNaN(value);
  };

  const isInfinity = (value) => {
    return typeof value === 'number' && !isFinite(value);
  };

  const isDate = (value) => {
    return typeof value === 'object' && value !== null && typeof value.getMonth === 'function';
  };

  const isUndefined = (value) => {
    return value === undefined && typeof value === 'undefined';
  };

  const isFunction = (value) => {
    return typeof value === 'function';
  };

  const isSymbol = (value) => {
    return typeof value === 'symbol';
  };

  const restOfDataTypes = (value) => {
    return isNumber(value) || isString(value) || isBoolean(value);
  };

  const ignoreDataTypes = (value) => {
    return isUndefined(value) || isFunction(value) || isSymbol(value);
  };

  const nullDataTypes = (value) => {
    return isNotNumber(value) || isInfinity(value) || isNull(value);
  }

  const arrayValuesNullTypes = (value) => {
    return isNotNumber(value) || isInfinity(value) || isNull(value) || ignoreDataTypes(value);
  }

  const removeComma = (str) => {
    const tempArr = str.split('');
    tempArr.pop();
    return tempArr.join('');
  };


  if (ignoreDataTypes(obj)) {
    return undefined;
  }

  if (isDate(obj)) {
    return `"${obj.toISOString()}"`;
  }

  if(nullDataTypes(obj)) {
    return `${null}`
  }

  if(isSymbol(obj)) {
    return undefined;
  }


  if (restOfDataTypes(obj)) {
    const passQuotes = isString(obj) ? `"` : '';
    return `${passQuotes}${obj}${passQuotes}`;
  }

  if (isArray(obj)) {
    let arrStr = '';
    obj.forEach((eachValue) => {
      arrStr += arrayValuesNullTypes(eachValue) ? JSONStringify(null) : JSONStringify(eachValue);
      arrStr += ','
    });

    return  `[` + removeComma(arrStr) + `]`;
  }

  if (isObject(obj)) {
      
    let objStr = '';

    const objKeys = Object.keys(obj);

    objKeys.forEach((eachKey) => {
        const eachValue = obj[eachKey];
        objStr +=  (!ignoreDataTypes(eachValue)) ? `"${eachKey}":${JSONStringify(eachValue)},` : '';
    });
    return `{` + removeComma(objStr) + `}`;
  }
};

Here is the link: https://javascript.plainenglish.io/create-your-own-implementation-of-json-stringify-simiplied-version-8ab6746cdd1

Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.