One Pager Cheat Sheet
- You can implement your own version of the
JSON.parse()
method, calledparseJSON
, that accepts one parameter and can return one of the following:array, object, string, number, boolean, or null
. - By defining multiple
if
cases to check fornull
, emptyobjects
,arrays
orbooleans
and additional parsing of values inside quotes and brackets, we can create a JSON Parser in JavaScript.
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
51
}
function parseJSON(input) {
// if the input is empty or starts with an invalid character, throw an error
if (input === "" || input[0] === "'") {
throw Error();
}
// check if the input is null, an empty object, empty array, or a boolean and return the value from the input
if (input === "null") {
return null;
}
if (input === "{}") {
return {};
}
if (input === "[]") {
return [];
}
if (input === "true") {
return true;
}
if (input === "false") {
return false;
}
//if the input starts with a quote, return the value from inside the quotes
if (input[0] === '"') {
return input.slice(1, -1);
}
// if it starts with a bracket, perform parsing of the contents within the brackets
if (input[0] === "{") {
return input
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Got more time? Let's keep going.
If you had any problems with this tutorial, check out the main forum thread here.