From 2ad18cda47734ede0c62bbf1aaa0fb70b273ee8a Mon Sep 17 00:00:00 2001 From: Shaban-Eissa Date: Sat, 1 Jun 2024 18:51:01 +0300 Subject: [PATCH] feat: implementation for JSON.parse() --- 22.implement-JSON-parse.md | 171 +++++++++++++++++++++++++++++++++++++ 1 file changed, 171 insertions(+) diff --git a/22.implement-JSON-parse.md b/22.implement-JSON-parse.md index eecba4a..c155b80 100644 --- a/22.implement-JSON-parse.md +++ b/22.implement-JSON-parse.md @@ -1,4 +1,5 @@ # 22. implement JSON.parse() +JSON.parse() is a JavaScript method used to parse a JSON string, constructing the JavaScript value or object described by the string. ### Problem @@ -162,3 +163,173 @@ function skipLeadingSpace(str) { return str.slice(firstNonSpaceCharIdx); } ``` + +# + +### Usage +```js +console.log(parse("1")); // 1 +console.log(parse("true")); // true +console.log(parse("null")); // null +console.log(parse('"abc"')); // abc +console.log(parse("false")); // false +console.log(parse("undefined")); // undefined +console.log(parse('{"a":1,"b":2}')); // { a: 1, b: 2 } +console.log(parse('["a", "b", "c"]')); // [ 'a', 'b', 'c' ] +console.log(parse(['{"a":1,"b":2}', '{"a":1,"b":2}'])); // [{ a: 1, b: 2 }, { a: 1, b: 2 }] +``` + +# + +### Explanation + +This code is a custom implementation of JSON.parse() function in JavaScript. It converts a JSON string into a JavaScript value. Here's a breakdown of the main functions: + +1. `parse(str)`: This is the main function that takes a JSON string and returns a JavaScript value. It first detects the type of the data using `detectDataType(str)`, and then calls the appropriate function to parse the data. + +2. `parseObj(str)`: This function parses a JSON object string into a JavaScript object. It iterates over the string, extracting keys and values, and then parses the values based on their detected data type. It throws an error if the string is not properly formatted. + +3. `parseArr(str)`: This function parses a JSON array string into a JavaScript array. It iterates over the string, extracting items, and then parses the items based on their detected data type. It throws an error if the string is not properly formatted. + +4. `parsePrimitive(str)`: This function parses a JSON primitive string (number, string, boolean, null, or undefined) into a JavaScript primitive value. It handles each type of primitive separately. + +5. `detectDataType(str)`: This function detects the type of a JSON string. It checks the first and last characters of the string to determine if it's an object, array, or primitive. + +6. `skipLeadingSpace(str)`: This function removes leading whitespace from a string. It finds the index of the first non-space character and slices the string from that index. + +# + +### Real World Examples + +Here are some real-world examples of its use: + +### 1. Retrieving Data from Local Storage + +When you store data in local storage as a JSON string, you need to parse it back into a JavaScript object when retrieving it. + +**Example:** + +```javascript +// Retrieve the JSON string from local storage +const userString = localStorage.getItem('user'); + +// Parse the JSON string to a JavaScript object +const user = JSON.parse(userString); + +console.log(user); +// Output: { name: "Alice", age: 25, preferences: { theme: "dark", language: "en" } } +``` + +### 2. Receiving Data from a Server + +When you receive JSON data from a server, you need to parse it to use it as a JavaScript object. + +**Example:** + +```javascript +fetch('https://api.example.com/products/123') + .then(response => response.json()) // .json() automatically parses JSON + .then(data => { + // data is already parsed as a JavaScript object + console.log(data); + }) + .catch(error => console.error('Error:', error)); +``` + +### 3. Parsing Configuration Files + +If your application reads configuration data from a JSON file, you need to parse it into a JavaScript object. + +**Example:** + +```javascript +const configString = ` +{ + "apiKey": "12345", + "theme": "dark", + "language": "en" +}`; + +// Parse the JSON string to a JavaScript object +const config = JSON.parse(configString); + +console.log(config); +// Output: { apiKey: "12345", theme: "dark", language: "en" } +``` + +### 4. Processing JSON Data from an API + +When you interact with an API that returns JSON data, you need to parse the response to manipulate the data. + +**Example:** + +```javascript +const jsonResponse = '{"name": "Bob", "age": 30, "isAdmin": false}'; + +// Parse the JSON string to a JavaScript object +const user = JSON.parse(jsonResponse); + +console.log(user.name); // Output: Bob +console.log(user.age); // Output: 30 +console.log(user.isAdmin); // Output: false +``` + +### 5. Handling Dynamic Data + +When dealing with dynamic data sources such as user input or third-party services that provide JSON, you need to parse the input to work with it. + +**Example:** + +```javascript +const userInput = '{"searchTerm": "JavaScript", "resultsPerPage": 10}'; + +// Parse the JSON string to a JavaScript object +const searchParameters = JSON.parse(userInput); + +console.log(searchParameters.searchTerm); // Output: JavaScript +console.log(searchParameters.resultsPerPage); // Output: 10 +``` + +### 6. Parsing Nested JSON Data + +When working with nested JSON data structures, JSON.parse() is essential for converting the string to an object. + +**Example:** + +```javascript +const nestedJsonString = ` +{ + "name": "John", + "address": { + "street": "123 Main St", + "city": "New York", + "zip": "10001" + }, + "phones": ["555-1234", "555-5678"] +}`; + +// Parse the JSON string to a JavaScript object +const person = JSON.parse(nestedJsonString); + +console.log(person.address.city); // Output: New York +console.log(person.phones[1]); // Output: 555-5678 +``` + +### 7. Parsing JSON with Error Handling + +When parsing JSON, it is good practice to handle potential errors, especially with user input or data from unreliable sources. + +**Example:** + +```javascript +const invalidJsonString = '{"name": "John", "age": 30'; // Missing closing bracket + +try { + const user = JSON.parse(invalidJsonString); + console.log(user); +} catch (error) { + console.error('Invalid JSON:', error.message); +} +// Output: Invalid JSON: Unexpected end of JSON input +``` +