1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS
1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS

How To Parse A JSON Array In JavaScript, With Exception Handling

ReadTime: 4 minutes

JSON (JavaScript Object Notation) is a lightweight data interchange format, widely used for sending and receiving data between a server and a web application. In JavaScript, parsing a JSON array involves converting a JSON string into a JavaScript object or array.


Parsing a JSON Array in JavaScript

JSON (JavaScript Object Notation) is a widely used format for data interchange. When dealing with a JSON array, we need to convert a JSON string into a JavaScript array using JSON.parse(). This method takes a JSON string and returns the corresponding JavaScript object or array.

However, it's important to handle exceptions properly, as JSON.parse() throws a SyntaxError if the input is invalid.

Example:

javascript
const jsonString = '[{"id": 1, "name": "apple"}, {"id": 2, "name": "banana"}]';

try {
  const jsonArray = JSON.parse(jsonString);
  console.log(jsonArray);
} catch (error) {
  console.error('Invalid JSON:', error.message);
}
Example of Parsing Json Array as String

If jsonString is valid, JSON.parse() successfully converts it into a JavaScript array. But if the string contains malformed JSON, a SyntaxError will be thrown.


Handling Invalid JSON

To gracefully handle errors, we can catch exceptions using a try...catch block.

Example of Invalid JSON:

javascript
const invalidJson = '[{"id": 1, "name": "apple",]';  // Malformed JSON

try {
  const jsonArray = JSON.parse(invalidJson);
  console.log(jsonArray);
} catch (error) {
  console.error('Invalid JSON:', error.message);
}
Handling Invalid JSON

This prevents your code from crashing and allows proper error handling.

Ensure your JSON is valid by using a JSON validator, especially when dealing with external data. You can even use a try-catch block. If there is error in parsing JSON, then you will get SyntaxError exception.

πŸ§ͺPractice Coding Problem: Handling JSON Array Parsing Errors

In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.

Write a JavaScript function named safeParseJSON that takes a JSON string as input and returns the parsed JSON array if valid. If the JSON is invalid, catch the error and return an informative message.

Problem (JavaScript)

javascript
function safeParseJSON(jsonString) {
  // > > > πŸ‘‰ Write code here πŸ‘ˆ < < <
}

// Example usage:
const validJsonString = '[{"id": 1, "name": "apple"}, {"id": 2, "name": "banana"}]';
const invalidJsonString = "['apple', 'banana']";

const validResult = safeParseJSON(validJsonString);
console.log(validResult); // Output: Parsed JSON array

const invalidResult = safeParseJSON(invalidJsonString);
console.log(invalidResult); // Output: "Invalid JSON: ..."
Problem Code

Please attempt before seeing the Answer:

Solution
javascript
function safeParseJSON(jsonString) {
  try {
      const parsedJSON = JSON.parse(jsonString);

      // Check if the parsed result is an array
      if (Array.isArray(parsedJSON)) {
          return parsedJSON;
      } else {
          throw new Error('Invalid JSON: Not an array.');
      }
  } catch (error) {
      return `Invalid JSON: ${error.message}`;
  }
}
Solution Code

Explanation:

  • The safeParseJSON function attempts to parse the input JSON string using JSON.parse() within a try block.
  • If parsing is successful and the result is an array, it returns the parsed array.
  • If parsing fails or the result is not an array, it throws a custom error message within the catch block.
  • The catch block then returns an informative error message, indicating that the JSON is invalid.
  • The example usage demonstrates how the function handles both valid and invalid JSON strings.

Parsing JSON arrays in JavaScript is a fundamental skill for developers working with web applications (Frontend or Backend). Understanding how to use JSON.parse() and handling potential errors ensures smooth integration of JSON data into your JavaScript code. Validate your JSON, keep an eye on data types, and parse away! πŸš€πŸ”

Contact

Feel free to reach out!