🗂️ JsonManager
A utility class for managing JSON data in memory and on disk. Supports loading, saving, reading, updating, and deleting nested keys using dot-separated paths.
Import
1import { JsonManager } from "hbh-nodes";
constructor(initialData = {})
Creates a new JsonManager instance with optional initial data.
Parameters:
initialData(object, optional) – Starting JSON data. Defaults to an empty object.
Example:
1const jm = new JsonManager({ user: { name: "Alice" } });
static async loadFromFile(filePath)
Loads JSON data from a file and returns a JsonManager instance.
Parameters:
filePath(string) – Path to the JSON file.
Returns:
Promise<JsonManager> – A new instance containing the loaded data.
Example:
1const jm = await JsonManager.loadFromFile("./data.json");
Edge Cases:
- Throws an error if the file does not exist or contains invalid JSON.
async saveToFile(filePath)
Saves the current JSON data to a file.
Parameters:
filePath(string) – Path where the JSON should be written.
Returns:
Promise<void>
Example:
1await jm.saveToFile("./data.json");
Edge Cases:
- Overwrites the file if it already exists.
- Throws an error if the write operation fails.
get(path)
Retrieves a value from nested JSON using a dot-separated path.
Parameters:
path(string) – Dot-separated key path (e.g.,"user.name").
Returns:
The value at the given path or undefined if not found.
Example:
1const name = jm.get("user.name"); // "Alice"
set(path, value)
Sets a value in nested JSON using a dot-separated path. Creates intermediate objects if needed.
Parameters:
path(string) – Dot-separated key path.value– Value to set.
Example:
1jm.set("user.age", 25);
delete(path)
Deletes a key in nested JSON using a dot-separated path.
Parameters:
path(string) – Dot-separated key path.
Example:
1jm.delete("user.age");
print()
Pretty-prints the current JSON data to the console.
Example:
1jm.print();2/*3{4 "user": {5 "name": "Alice"6 }7}8*/