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
ifcases to check fornull, emptyobjects,arraysorbooleansand 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.
xxxxxxxxxx51
}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 inputThat's all we've got! Let's move on to the next tutorial.
If you had any problems with this tutorial, check out the main forum thread here.