JSON Encoding and Decoding - potatoscript/json GitHub Wiki

🎯 JSON Encoding and Decoding: Unlocking the Magic! πŸ§™β€β™‚οΈβœ¨

Welcome to the Secret World of JSON Encoding and Decoding! πŸ”
Imagine you’re a secret agent πŸ•΅οΈβ€β™‚οΈ encrypting and decrypting messages.
In the world of JSON, Encoding and Decoding do the same thing β€” they transform data to and from a secret format! 🎁


πŸ“š What is JSON Encoding and Decoding?

  • Encoding (Serialization):
    Converts a JavaScript object into a JSON string. πŸ“
    ➑️ Think of it as turning an object into a letter to send to someone.

  • Decoding (Deserialization):
    Converts a JSON string back into a JavaScript object. πŸ”„
    ➑️ It’s like receiving a letter and understanding what it says.


πŸ§™β€β™‚οΈ 1. Encoding: Turning Object to JSON (Stringify)

When you need to send or store an object, you encode it into a JSON string.
JavaScript uses JSON.stringify() to serialize the object. 🧾


🎯 Example: Encode an Object into a JSON String

let person = {
  name: "Lucy",
  age: 25,
  hobbies: ["reading", "coding", "traveling"]
};

// Encode (serialize) JavaScript object to JSON string
let jsonString = JSON.stringify(person);

console.log(jsonString);

πŸ” Result:

{"name":"Lucy","age":25,"hobbies":["reading","coding","traveling"]}

βœ… Explanation:

  • JSON.stringify() takes a JavaScript object and converts it into a JSON string.
  • Perfect for sending data to a server or saving it in local storage. πŸ“‘

πŸ§™β€β™‚οΈ 2. Decoding: Turning JSON to Object (Parse)

When you receive JSON data from an API or local storage, you decode it back into an object.
JavaScript uses JSON.parse() to deserialize the JSON string. πŸ“œ


🎯 Example: Decode a JSON String to an Object

let jsonString = '{"name":"Lucy","age":25,"hobbies":["reading","coding","traveling"]}';

// Decode (deserialize) JSON string to JavaScript object
let person = JSON.parse(jsonString);

console.log(person.name);  // Output: Lucy
console.log(person.age);   // Output: 25
console.log(person.hobbies[0]);  // Output: reading

βœ… Explanation:

  • JSON.parse() takes a JSON string and converts it into a JavaScript object.
  • You can now access and manipulate the object easily! ✨

⚑ 3. Advanced Encoding: Handling Special Cases

You can control how JSON is encoded by customizing JSON.stringify()! 🎁
Use a replacer function or an array of keys to filter and modify data during encoding. πŸ”„


🎯 Example: Filter Keys During Encoding

let person = {
  name: "Lucy",
  age: 25,
  password: "secret123",
  hobbies: ["reading", "coding"]
};

// Encode only specific keys
let jsonString = JSON.stringify(person, ["name", "age"]);

console.log(jsonString);
// Output: {"name":"Lucy","age":25}

βœ… Explanation:

  • Only name and age are included in the final JSON string.
  • password and hobbies are excluded from the encoded data. πŸ”

🎯 Example: Using Replacer Function

let person = {
  name: "Lucy",
  age: 25,
  password: "secret123",
  hobbies: ["reading", "coding"]
};

// Customize encoding with replacer function
let jsonString = JSON.stringify(person, (key, value) => {
  if (key === "password") {
    return undefined;  // Exclude password
  }
  return value;
});

console.log(jsonString);
// Output: {"name":"Lucy","age":25,"hobbies":["reading","coding"]}

βœ… Explanation:

  • The replacer function removes sensitive data (like password).
  • This makes the encoded JSON safe to share or store! πŸ”

πŸ§™β€β™‚οΈ 4. Advanced Decoding: Reviver in JSON.parse()

When decoding, you can use a reviver function to modify values as they are parsed. πŸ”₯
Perfect for transforming or validating data while decoding!


🎯 Example: Using Reviver to Modify Values

let jsonString = '{"name":"Lucy","age":"25","hobbies":["reading","coding"]}';

// Use reviver to convert age to number
let person = JSON.parse(jsonString, (key, value) => {
  if (key === "age") {
    return parseInt(value);  // Convert age to number
  }
  return value;
});

console.log(person.age);  // Output: 25 (number)

βœ… Explanation:

  • reviver converts the age from string to number while decoding.
  • Handy for ensuring consistent data types. βœ…

πŸ•ΉοΈ 5. Formatting JSON Strings: Pretty Print

Want to make JSON strings more readable? Use pretty printing with JSON.stringify()! ✨


🎯 Example: Pretty Print JSON with Indentation

let person = {
  name: "Lucy",
  age: 25,
  hobbies: ["reading", "coding", "traveling"]
};

// Pretty print with 2-space indentation
let jsonString = JSON.stringify(person, null, 2);

console.log(jsonString);

βœ… Result:

{
  "name": "Lucy",
  "age": 25,
  "hobbies": [
    "reading",
    "coding",
    "traveling"
  ]
}

βœ… Explanation:

  • Third parameter (2) controls indentation for pretty printing.
  • Improves readability for debugging or documentation. 🎯

πŸ“¦ 6. Encoding/Decoding JSON Arrays

JSON arrays are very common! They store multiple objects and can be encoded/decoded easily. πŸ“š


🎯 Example: Encode and Decode JSON Array

let people = [
  { name: "Lucy", age: 25 },
  { name: "Berry", age: 26 },
  { name: "Snoopy", age: 5 }
];

// Encode JSON Array
let jsonString = JSON.stringify(people);
console.log(jsonString);

// Decode JSON Array
let decodedArray = JSON.parse(jsonString);
console.log(decodedArray[1].name);  // Output: Berry

βœ… Explanation:

  • JSON arrays are encoded and decoded just like objects.
  • Access array elements using indexes. πŸ“š

🧩 7. Handling Errors in Encoding/Decoding

When encoding or decoding goes wrong, handle errors gracefully using try...catch. πŸ”₯


🎯 Example: Error Handling in JSON.parse()

let invalidJson = "{ name: 'Lucy' }";  // Invalid JSON!

try {
  let data = JSON.parse(invalidJson);
} catch (error) {
  console.error("Oops! JSON error:", error.message);
}

βœ… Explanation:

  • try...catch prevents your application from crashing when JSON parsing fails.
  • Always validate incoming JSON data. βœ…

πŸ› οΈ 8. JSON in Real Life: Local Storage Encoding/Decoding

You can save and retrieve JSON in local storage using JSON.stringify() and JSON.parse()! πŸ—„οΈ


🎯 Example: Save and Retrieve JSON in Local Storage

let user = { name: "Lucy", age: 25 };

// Encode and save to local storage
localStorage.setItem("user", JSON.stringify(user));

// Retrieve and decode from local storage
let storedUser = JSON.parse(localStorage.getItem("user"));

console.log(storedUser.name);  // Output: Lucy

βœ… Explanation:

  • Use JSON.stringify() to store objects as JSON strings in local storage.
  • Retrieve and decode with JSON.parse() when needed. πŸ“š

🎁 9. JSON and APIs: Sending and Receiving Data

When working with APIs, JSON encoding/decoding is essential. 🌐


🎯 Example: Sending JSON with fetch()

let user = { name: "Lucy", age: 25 };

// Send data to server using POST request
fetch("https://api.example.com/user", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(user)
});

βœ… Explanation:

  • JSON.stringify() converts the object to a string for transmission.
  • The API processes the JSON string on the server.

🧠 10. Tips and Tricks for Encoding/Decoding

🎯 Always validate JSON data before parsing to avoid errors.
🎯 Use JSON.stringify() for pretty printing with indentation when debugging.
🎯 Handle exceptions using try...catch to avoid breaking the application.