Data Serialization & JSON API
In the world of web development, systems need to talk to each other. They don't send memory addresses; they send raw text. JSON (JavaScript Object Notation) is the universal language they use.
JSON vs JS Objects
A common misconception is that a JavaScript Object and JSON are the same thing. They are not. JSON is a text format. While JS Objects allow unquoted keys (like name: "Alice") and complex values (like functions), JSON requires strictly formatted double-quoted strings for all keys (like "name": "Alice") and only supports strings, numbers, booleans, arrays, nested objects, and null.
JSON.stringify()
When you need to send an object to a server or save it to localStorage, you must convert it to a string.JSON.stringify(obj) does exactly this. It strips out anything it can't serialize (like functions or undefined properties) and outputs a perfect JSON string.
JSON.parse()
When the server replies with data, it arrives as a text string. Trying to access properties on a string will yield undefined. You must deserialize it using JSON.parse(stringData). Be warned: parsing malformed JSON will crash your script with a SyntaxError.
Advanced Formatting Trick+
Did you know JSON.stringify accepts three arguments? The syntax is JSON.stringify(value, replacer, space). If you pass JSON.stringify(obj, null, 2), it will format the resulting string with 2 spaces of indentation, making it highly readable for humans or logs!
