-
Notifications
You must be signed in to change notification settings - Fork 3
LiteJsonDb Utility Functions
These functions are designed to make your coding life easier, more organized, and a bit more fun. 🌟
Utility functions are your best friends when it comes to writing clean, efficient, and reusable code. By using these pre-built helpers, you avoid rewriting the same logic over and over again, which means fewer bugs and more time for enjoying coding (or coffee breaks ☕). Plus, they're like the Swiss Army knife of coding—compact, versatile, and incredibly handy.
To kick things off with LiteJsonDb
, initialize your database. You can even enable encryption if you want that extra layer of security!
import LiteJsonDb # Initialize the database with encryption enabled db = LiteJsonDb.JsonDB(crypted=True)
Here’s a run-down of the utility functions you’ll find super useful:
Convert a string to a datetime object. Perfect for handling date and time data.
if "profile" in data and "joined" in data["profile"]: joined_date = db.convert_to_datetime(data["profile"]["joined"]) print("\nJoined Date:", joined_date) else: print("No join date found for user 1.")
Fetch a value from your data or return a default if the key is not found.
name = db.get_or_default(data, "name", "Anonymous") print("\nName:", name)
Check if a key is present in your data; if not, add it with a default value.
db.key_exists_or_add(data, "Nickname", "Ali") print("\nData with Nickname:") db.pretty_print(data)
Convert all keys in your dictionary to lowercase for consistency.
normalized_data = db.normalize_keys(data) print("\nNormalized Keys:") db.pretty_print(normalized_data)
Transform nested JSON into a flat dictionary. Great for simplifying complex structures!
normalized_data = db.flatten_json(data) print("\nFlattened JSON:") db.pretty_print(normalized_data)
Filter your list based on a condition. Perfect for sifting through data.
data_list = [{"name": "Aliou", "age": 35}, {"name": "Max", "age": 21}] filtered_data = db.filter_data(data_list, lambda d: d["age"] > 25) print("\nFiltered Data:") db.pretty_print(filtered_data)
Sort your data by a specific key. Whether ascending or descending, it’s all under control.
sorted_data = db.sort_data(data_list, lambda d: d["age"]) print("\nSorted Data:") db.pretty_print(sorted_data)
Hash a password using SHA-256 to keep it secure and out of reach from prying eyes.
password = "securepassword123" hashed = db.hash_password(password) print("\nHashed Password:", hashed)
Verify if the given password matches the hashed one. Security at its finest!
is_correct = db.check_password(hashed, password) # change value to check print("Password Verification:", is_correct) # True
Protect against XSS attacks by sanitizing your output. Keeping your app safe and sound! [XSS VULNERABILITY IS EVERYWHERE :)]
unsanitized_data = {"bio": "<script>alert('hack');</script>"}sanitized_data = db.sanitize_output(unsanitized_data) print("\nSanitized Output:") db.pretty_print(sanitized_data)
Here’s a full example showing how you can put these functions to work:
import LiteJsonDb
# Initialize the database with encryption enabled
db = LiteJsonDb.JsonDB(crypted=True)
# Editing data
db.edit_data("users/1", {
"profile": {
"joined": "2023-08-04",
"name": "John Doe",
"age": 30
}
})
data = db.get_data("users/1")
# Convert to Datetime
if "profile" in data and "joined" in data["profile"]:
joined_date = db.convert_to_datetime(data["profile"]["joined"])
print("\nJoined Date:", joined_date)
else:
print("No join date found for user 1.")
# Get or Default
name = db.get_or_default(data, "name", "Anonymous")
print("\nName:", name)
# Key Exists or Add
db.key_exists_or_add(data, "Nickname", "Ali")
print("\nData with Nickname:")
db.pretty_print(data)
# Flatten JSON
normalized_data = db.flatten_json(data)
print("\nFlattened JSON:")
db.pretty_print(normalized_data)
# Normalize Keys
normalized_data = db.normalize_keys(data)
print("\nNormalized Keys:")
db.pretty_print(normalized_data)
# Filter Data
data_list = [{"name": "Aliou", "age": 35}, {"name": "Max", "age": 21}]
filtered_data = db.filter_data(data_list, lambda d: d["age"] > 25)
print("\nFiltered Data:")
db.pretty_print(filtered_data)
# Sort Data
sorted_data = db.sort_data(data_list, lambda d: d["age"])
print("\nSorted Data:")
db.pretty_print(sorted_data)
# Hash Password
password = "securepassword123"
hashed = db.hash_password(password)
print("\nHashed Password:", hashed)
is_correct = db.check_password(hashed, password) # change value to check
print("Password Verification:", is_correct) # True
# Sanitize Output
unsanitized_data = {"bio": "<script>alert('hack');</script>"}
sanitized_data = db.sanitize_output(unsanitized_data)
print("\nSanitized Output:")
db.pretty_print(sanitized_data)
# Retrieve the complete database
print(db.get_db(raw=True))
Feel free to explore these functions and make your code more efficient and secure. Happy coding! 🚀