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
nameandageare included in the final JSON string. passwordandhobbiesare 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
replacerfunction removes sensitive data (likepassword). - 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:
reviverconverts theagefrom 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...catchprevents 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.