JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write for humans and machines. It is commonly used to exchange data between a server and a client or between different systems.
When working with JSON, formatting and validation are essential to ensure the data is syntactically correct and easy to read. Properly formatted JSON enhances readability, while validation ensures the JSON structure adheres to standard rules.
If you're working with JSON in JavaScript, you can use the built-in JSON object for parsing, validating, and stringifying JSON data.
JSON.stringify()
The JSON.stringify()
method converts a JavaScript object into a JSON string. You can also add formatting (pretty-printing) using its optional arguments. Example:
const data = { name: "John Doe", age: 30, skills: ["JavaScript", "HTML", "CSS"] }; const formattedJSON = JSON.stringify(data, null, 2); // Pretty-print with 2-space indentation console.log(formattedJSON); /* Output: { "name": "John Doe", "age": 30, "skills": [ "JavaScript", "HTML", "CSS" ] } */
JSON.parse()
The JSON.parse()
method parses a JSON string and converts it into a JavaScript object. If the JSON string is invalid, it throws an error, making it a useful tool for validation. Example:
const jsonString = '{"name": "Jane Doe", "age": 25}'; try { const parsedData = JSON.parse(jsonString); // Valid JSON console.log(parsedData); // Output: { name: 'Jane Doe', age: 25 } } catch (error) { console.error("Invalid JSON:", error.message); }
If the JSON string contains errors (e.g., missing quotes, extra commas) JSON.parse()
will throw an error. Example:
const invalidJSONString = '{"name": "John", "age": 30,'; // Invalid JSON (trailing comma) try { const parsedData = JSON.parse(invalidJSONString); console.log(parsedData); } catch (error) { console.error("Error:", error.message); // Output: Error: Unexpected end of JSON input }