Loops & Iteration
Iterate over arrays with @djson for directive. Support for nested loops, loop variables (_index, _first, _last), and complex data structures.
A lightweight PHP library for creating dynamic JSON with loops, conditionals, and variables
JSON Template:
{
"products": {
"@djson for products as product": {
"name": "{​{product.name}​}",
"price": "{​{product.price}​}",
"@djson if product.onSale": {
"discount": {
"original": "{​{product.price}​}",
"sale": "{​{product.salePrice}​}"
}
}
}
}
}PHP Code:
use Qoliber\DJson\DJson;
$djson = new DJson();
$template = file_get_contents('template.json');
$data = [
'products' => [
['name' => 'Laptop', 'price' => 999, 'onSale' => true, 'salePrice' => 799],
['name' => 'Mouse', 'price' => 29, 'onSale' => false]
]
];
echo $djson->processToJson($template, $data, JSON_PRETTY_PRINT);Output:
{
"products": [
{
"name": "Laptop",
"price": 999,
"discount": {
"original": 999,
"sale": 799
}
},
{
"name": "Mouse",
"price": 29
}
]
}composer require qoliber/djsonBorn from E-commerce Needs
DJson was created to solve a real problem: generating complex JSON structures for e-commerce platforms. When building product catalogs, API responses, and structured data (like Schema.org JSON-LD), we needed a way to create dynamic JSON that was:
What started as an e-commerce solution has become a powerful library for any JSON generation needs.
Key Benefits:
@djson prefix, making templates readable| Feature | Syntax | Description |
|---|---|---|
| Variables | {​{variable}​} | Dynamic value insertion |
| Loops | @djson for items as item | Iterate over arrays |
| Conditionals | @djson if condition | Show/hide content |
| Match/Switch | @djson match variable | Pattern matching |
| Computed | @djson set total = a * b | Calculate values |
| Functions | @djson upper {​{name}​} | Transform data |
| Ternary | {​{condition ? yes : no}​} | Inline conditions |
| Logical | condition && other | Complex logic |
New to DJson? Start with the Getting Started Guide to learn the basics.
Want to see examples? Check out Real-World Examples for common use cases.
Need API details? Browse the API Reference for complete documentation.