1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
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.
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.
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);
}
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.
To gracefully handle errors, we can catch exceptions using a try...catch
block.
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);
}
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.
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)
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: ..."
Please attempt before seeing the Answer:
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}`;
}
}
Explanation:
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! ππ
Feel free to reach out!