Good morning! Here's our prompt for today.
In Javascript there is a method called JSON.stringify()
that can convert an object or a variable into a JSON string. The method handles different data types differently, ending up with its correct JSON "translation". Some examples of how this method handles different types include:
Boolean
,Number
, andString
objects are converted to the corresponding primitive valuesundefined
,Function
, andSymbol
are not valid JSON values and are changed tonull
- The instances of
Date
are returned asdate.toISOString()
and are treated as strings Infinity
as well as the valuenull
are considered asnull
Can you implement a simplified version of this JSON stringifier, covering the most important constraints when it comes to the data type and value handling?
Here is an example of how your solution should work:
1stringify({}); // '{}'
2stringify(true); // 'true'
3stringify('foo'); // '"foo"'
4stringify([1, 'false', false]); // '[1,"false",false]'
5stringify([null, Infinity]); // '[null,null]'
6stringify({ x: 5 }); // '{"x":5}'

Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
function stringify(data) {
if (typeof data === "string") {
return `"${data}"`;
}
if (typeof data === "function") {
return undefined;
}
if (data === Infinity || data === -Infinity || data === null
|| data === undefined || typeof data === "symbol") {
return "null";
}
if (typeof data === "number" || typeof data === "boolean") {
return `${data}`;
}
if (data instanceof Date) {
return `"${data.toISOString()}"`;
}
if (Array.isArray(data)) {
const arr = data.map((el) => stringify(el));
return `[${arr.join(",")}]`;
}
if (typeof data === "object") {
const arr = Object.entries(data).reduce((acc, [key, value]) => {
if (value === undefined) {
return acc;
}
acc.push(`"${key}":${stringify(value)}`);
return acc;
Here's how we would solve this problem...
How do I use this guide?
Solution
Our solution would be the method stringify
, that will simply handle the cases we mentioned above, with many different if
conditions. For example, we return undefined
if the type of the data is a function, or we return null
if it is a synbol, undefined, infinity, or null.
1if (typeof data === "function") {
2 return undefined;
3}
4if (data === Infinity || data === -Infinity || data === null
5 || data === undefined || typeof data === "symbol") {
6 return "null";
7}
If the data is a string, number or a boolean, we return the data itself, bearing in mind the quotes needed for a string value.
1if (typeof data === "string") {
2 return `"${data}"`;
3}
4if (typeof data === "number" || typeof data === "boolean") {
5 return `${data}`;
6}
If our data type is a date, as stated above, we return it as a string, by using data.toISOString()
.
In case we are dealing with an array, or an object, then we need a bit more logic to parse our data. So, for an array, we will first map and stringify our data to make sure the elements are all in a string format, and then we are going to parse it in the needed JSON array format, using braces, and separate the data with commas:
1if (Array.isArray(data)) {
2 const arr = data.map((el) => stringify(el));
3 return `[${arr.join(",")}]`;
4}
For objects, we will handle them by looping the object properties one by one, and then using the reduce
method we will divide them into key-value pairs - key being the property name, and the value being its value. We will perserve the JSON objects notation, wrapping the object properties into brackets, and in the format "key": "value"
.
1if (typeof data === "object") {
2 const arr = Object.entries(data).reduce((acc, [key, value]) => {
3 if (value === undefined) {
4 return acc;
5 }
6 acc.push(`"${key}":${stringify(value)}`);
7 return acc;
8 }, []);
9 return `{${arr.join(",")}}`;
10}
Our final solution with all these conditions handled would look like this:
1function stringify(data) {
2 if (typeof data === "string") {
3 return `"${data}"`;
4 }
5 if (typeof data === "function") {
6 return undefined;
7 }
8 if (data === Infinity || data === -Infinity || data === null
9 || data === undefined || typeof data === "symbol") {
10 return "null";
11 }
12 if (typeof data === "number" || typeof data === "boolean") {
13 return `${data}`;
14 }
15
16 if (data instanceof Date) {
17 return `"${data.toISOString()}"`;
18 }
19 if (Array.isArray(data)) {
20 const arr = data.map((el) => stringify(el));
21 return `[${arr.join(",")}]`;
22 }
23 if (typeof data === "object") {
24 const arr = Object.entries(data).reduce((acc, [key, value]) => {
25 if (value === undefined) {
26 return acc;
27 }
28 acc.push(`"${key}":${stringify(value)}`);
29 return acc;
30 }, []);
31 return `{${arr.join(",")}}`;
32 }
33}
One Pager Cheat Sheet
- You can create a simplified version of the
JSON.stringify()
method to correctly handle different data types and values in order to successfully "translate" them into JSON strings. - We bold implemented a
stringify
method that handles different data types, such as functions, strings, numbers, booleans, dates, arrays, and objects, returning the corresponding strings ornull
as needed.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
}
function stringify(data) {
if (typeof data === "string") {
return `"${data}"`;
}
if (typeof data === "function") {
return undefined;
}
if (data === Infinity || data === -Infinity || data === null
|| data === undefined || typeof data === "symbol") {
return "null";
}
if (typeof data === "number" || typeof data === "boolean") {
return `${data}`;
}
if (data instanceof Date) {
return `"${data.toISOString()}"`;
}
if (Array.isArray(data)) {
const arr = data.map((el) => stringify(el));
return `[${arr.join(",")}]`;
}
if (typeof data === "object") {
const arr = Object.entries(data).reduce((acc, [key, value]) => {
if (value === undefined) {
return acc;
}
acc.push(`"${key}":${stringify(value)}`);
return acc;
}, []);
return `{${arr.join(",")}}`;
}
Got more time? Let's keep going.
If you had any problems with this tutorial, check out the main forum thread here.