You may already be familiar with the function JSON.stringify, which can be useful when comparing objects, implementing RESTFUL APIs or simply deep cloning a javascript object (although, it’s not recommended).

In this article, we are going to talk about how to create our own simplified version of this method, and learn how to improve its implementation step by step, covering more and more cases as we progress.

Image for post

If you are not familiar with this function, let’s take a look at what MDN has to say about it:

The **_JSON.stringify()_** method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Its syntax can be written like this:

JSON.stringify(value[, replacer[, space]])

Where “value” is the object or value we want to convert to a string. We can leave out the other 2 parameters for this article to make it easier.


Testing data

Consider this case:

const sampleObj = {
   "name": "Juan",
   "age": 29,
   "address": {
      "street": "Street 1",
      "number": 3
   }
}

If we apply the origin JSON.stringify() function to that object, this is what we get:

{"name":"Juan","age":29,"address":{"street":"Street 1","number":3}}

As you can see, it’s fairly easy. It adds double quotes to the attributes, and if the value is a string it adds them too. For this particular example, we’ll only tackle those 3 data types: Number, String and Object. We’ll leave out Function, dates, undefined values and so, just to keep it simple, although, I recommend you read the documentation of JSON.stringify to see how it behaves with those types and others.

#js #recursion #javascript #json #json-stringify

Creating your own simplified implementation of JSON.stringify()
6.85 GEEK