@bonniernews/json-templates
v0.0.2
Published
Completes incomplete JSON string with caching capabilites
Maintainers
Readme
JSON Templates
A lightweight utility to substitute variables in strings, objects, and arrays. Built on top of json-templates, it adds smart stringification: objects injected into strings are automatically converted to JSON instead of [object Object].
Installation
npm install @bonniernews/json-templatesUsage
import { render } from "@bonniernews/json-templates";
const data = {
admin: { id: 1, name: "Alice" },
tags: ["security", "management"],
meta: { lastLogin: "2023-10-01" }
};
const template = {
// 1. Entire Object Substitution (Preserves Type)
user: "{{admin}}",
// 2. Array Indexing (Using dot notation)
primaryTag: "{{tags.0}}",
// 3. Smart Stringification (Automatic JSON inside strings)
summary: "User {{admin.name}} with tags {{tags}} logged in at {{meta.lastLogin}}"
};
const result = render(template, data);
/*
result = {
user: { id: 1, name: "Alice" }, // Becomes the raw object
primaryTag: "security", // Accesses first element
summary: "User Alice with tags [\"security\",\"management\"] logged in at 2023-10-01"
}
*/Features
- Deep Substitution: Recursively processes nested strings, objects, and arrays.
- Array Indexing: Access elements using dot notation (e.g.,
{{list.0}}). - Smart Coercion: Objects placed inside a string (e.g.
"val: {{obj}}") are automatically JSON stringified via a recursive Proxy. - Type Preservation: If a template string is exactly
{{myObj}}, it returns the original object/array type rather than a string.
API
render<T>(template: T, data: Record<string, any>): T
template: The source string, object, or array to process.data: The variables to inject.- Returns: The processed template with values substituted.
Acknowledgments
This library is a wrapper around the excellent json-templates by Mikael Brevik.
