PHPackages                             qoliber/djson - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. qoliber/djson

ActiveLibrary[Templating &amp; Views](/categories/templating)

qoliber/djson
=============

Dynamic JSON templating library with loops, conditions, and variables

1.5.0(6mo ago)22458↓47.2%1MITPHPPHP &gt;=8.1

Since Nov 13Pushed 6mo agoCompare

[ Source](https://github.com/qoliber/djson)[ Packagist](https://packagist.org/packages/qoliber/djson)[ RSS](/packages/qoliber-djson/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (2)Versions (7)Used By (0)

DJson - Dynamic JSON Templating Library
=======================================

[](#djson---dynamic-json-templating-library)

A powerful yet lightweight PHP library for creating dynamic JSON with loops, conditionals, functions, variables, and pattern matching. Think of it as a feature-rich templating engine specifically designed for JSON generation.

[![Tests](https://camo.githubusercontent.com/ef0ca2221c7cbc59f1e2609faa633328ba36596d94b6a4de72ac04570db9e7fc/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d3232392532307061737365642d627269676874677265656e)](https://github.com/qoliber/djson)[![Mutation Score](https://camo.githubusercontent.com/a2894058ed75bcfd1d25a3bcf4c1930c8bb5975d8a8a942ee6cf3653a194d31a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6d75746174696f6e25323073636f72652d3130302532352d627269676874677265656e)](https://github.com/qoliber/djson)[![PHP Version](https://camo.githubusercontent.com/6518db1335bf20fdff07253dc6d6d0cec955b5fb6a8ef1382ac6d73687ecc07f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e312d626c7565)](https://php.net)[![License](https://camo.githubusercontent.com/b8cadaa967891081f8f165695470689986c028821dd8a040132f6e661795dc0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c7565)](LICENSE)[![Security](https://camo.githubusercontent.com/1fef546dc86c818e718514e446141aadea90e5f1677f2ca33cb76e967c923b54/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f73656375726974792d6d616e6461746f72792d627269676874677265656e)](https://github.com/qoliber/djson)

🚀 Features
----------

[](#-features)

- **Variable Interpolation**: Use `{{variable}}` syntax with dot notation for nested access
- **Template Functions**: 30+ built-in functions (upper, lower, date, round, join, etc.)
- **Arithmetic Operations**: Perform calculations with `@set` directive
- **Loops**: Iterate over arrays with `@djson for` directive
- **Conditionals**: Include/exclude content with `@djson if`, `@djson unless`, `@djson exists`
- **Pattern Matching**: Switch/case logic with `@djson match` and `@djson switch`
- **Variable Assignment**: Set and calculate values with `@djson set`
- **Else Statements**: Full conditional logic with `@djson else`
- **Loop Helpers**: Access `_index`, `_key`, `_first`, `_last` in loops
- **Type Preservation**: Maintains data types (numbers, booleans, null)
- **Error Handling**: Comprehensive validation with detailed error messages
- **Security First**: Mandatory protection against dangerous functions (eval, exec, shell\_exec, etc.)
- **PHP 8.1+**: Modern PHP with constructor property promotion

📚 **Full Documentation**:

Installation
------------

[](#installation)

```
composer require qoliber/djson
```

Quick Start
-----------

[](#quick-start)

```
use Qoliber\DJson\DJson;

$djson = new DJson();

$template = [
    'greeting' => 'Hello {{name | upper}}!',
    'users' => [
        '@djson for users as user',
        'name' => '{{user.name}}',
        'email' => '{{user.email}}'
    ]
];

$data = [
    'name' => 'world',
    'users' => [
        ['name' => 'John', 'email' => 'john@example.com'],
        ['name' => 'Jane', 'email' => 'jane@example.com']
    ]
];

$result = $djson->process($template, $data);
// ['greeting' => 'Hello WORLD!', 'users' => [...]]
```

Security
--------

[](#security)

DJson takes security seriously with **mandatory protection** against dangerous function registration.

### What's Protected

[](#whats-protected)

```
// These are BLOCKED - throws InvalidArgumentException
$djson->registerFunction('exec', fn($cmd) => shell_exec($cmd));
$djson->registerFunction('eval', fn($code) => eval($code));
$djson->registerFunction('file_get_contents', fn($path) => file_get_contents($path));
// Error: "dangerous pattern 'exec'... use registerUnsafeFunction()"

// Trying the "unsafe" method? ALSO blocked! (troll mode activated)
$djson->registerUnsafeFunction('exec', fn($cmd) => shell_exec($cmd));
// Error: "Sorry matey, no unsafe functions allowed! Security is mandatory!"
```

### Protected Patterns

[](#protected-patterns)

- **Code Execution**: `eval`, `assert`, `call_user_func`
- **System Commands**: `exec`, `shell_exec`, `system`, `passthru`, `popen`, `proc_open`
- **Filesystem**: `file_get_contents`, `file_put_contents`, `unlink`, `chmod`, `rename`
- **Includes**: `include`, `require`, `include_once`, `require_once`
- **Serialization**: `unserialize`
- **Reflection**: `reflection`
- **Database Functions**: `mysqli`, `mysql_`, `pg_`, `sqlite`, `pdo`, `odbc_`, `sqlsrv_`, `oci_`

### Safe Functions Work Fine

[](#safe-functions-work-fine)

```
// These are SAFE and work perfectly
$djson->registerFunction('currency', fn($v, $s = '$') => $s . number_format($v, 2));
$djson->registerFunction('md5hash', fn($v) => md5($v));
$djson->registerFunction('base64', fn($v) => base64_encode($v));
$djson->registerFunction('truncate', fn($v, $len = 50) => substr($v, 0, $len) . '...');
```

### Why No Bypass?

[](#why-no-bypass)

Security is **mandatory, not optional**. If you need to execute system commands or access files, do it **outside the template system** where you have proper access controls. Templates are for rendering data, not executing code.

### Deep Code Inspection

[](#deep-code-inspection)

DJson uses **PHP Reflection** to inspect the actual source code of registered callables, not just function names:

```
// BLOCKED - Even though function name is safe, the code inside is dangerous!
$djson->registerFunction('process_data', function ($input) {
    return eval($input);  // Detected via reflection!
});
// Error: "callable's source code contains a call to prohibited function pattern 'eval'"

// BLOCKED - Database access detected in callable
$djson->registerFunction('get_user', function ($id) {
    return mysqli_query($conn, "SELECT * FROM users WHERE id = $id");
});
// Error: "callable's source code contains a call to prohibited function pattern 'mysqli'"
```

This means you **cannot bypass security** by wrapping dangerous functions inside safe-looking closures. DJson analyzes the actual implementation and blocks any dangerous code patterns.

Core Features
-------------

[](#core-features)

### Variable Interpolation with Functions

[](#variable-interpolation-with-functions)

```
$template = [
    'title' => '{{product.name | upper}}',
    'price' => '{{product.price | number_format(2)}}',
    'date' => '{{timestamp | date("Y-m-d")}}'
];
```

### Loops with Special Variables

[](#loops-with-special-variables)

```
$template = [
    'items' => [
        '@djson for products as product',
        'position' => '{{_index}}',        // Current index
        'isFirst' => '{{_first}}',         // true if first item
        'isLast' => '{{_last}}',           // true if last item
        'name' => '{{product.name}}'
    ]
];
```

### Conditionals with Else

[](#conditionals-with-else)

```
$template = [
    '@djson if user.isPremium',
    'status' => 'Premium Member',
    '@djson else',
    'status' => 'Free User'
];
```

### Pattern Matching (Switch/Case)

[](#pattern-matching-switchcase)

```
$template = [
    '@djson match status',
    '@djson case active',
    'message' => 'User is active',
    '@djson case pending',
    'message' => 'Awaiting approval',
    '@djson default',
    'message' => 'Status unknown'
];
```

### Arithmetic Operations

[](#arithmetic-operations)

```
$template = [
    '@djson set total = price * quantity',
    '@djson set discount = total * 0.1',
    '@djson set final = total - discount',
    'finalPrice' => '{{final | number_format(2)}}'
];
```

### Conditional Expressions

[](#conditional-expressions)

```
$template = [
    '@djson if stock > 0',
    'available' => true,
    '@djson unless stock < 10',
    'lowStock' => false
];
```

Built-in Template Functions
---------------------------

[](#built-in-template-functions)

### String Functions

[](#string-functions)

- `upper`, `lower`, `capitalize`, `title`
- `trim`, `escape`, `slug`
- `substr`, `replace`

### Number Functions

[](#number-functions)

- `number_format`, `round`, `ceil`, `floor`, `abs`

### Array Functions

[](#array-functions)

- `count`, `first`, `last`, `join`, `sort`, `unique`

### Date Functions

[](#date-functions)

- `date`, `strtotime`

### Utility Functions

[](#utility-functions)

- `default`, `coalesce`
- `json_encode`

See full function documentation at [djson.dev/functions](https://djson.dev)

Advanced Examples
-----------------

[](#advanced-examples)

### E-commerce Product with Calculations

[](#e-commerce-product-with-calculations)

```
$template = [
    'product' => '{{name}}',
    '@djson set subtotal = price * quantity',
    '@djson set tax = subtotal * 0.2',
    '@djson set total = subtotal + tax',
    'pricing' => [
        'subtotal' => '{{subtotal | number_format(2)}}',
        'tax' => '{{tax | number_format(2)}}',
        'total' => '{{total | number_format(2)}}'
    ]
];
```

### Complex Conditional Logic

[](#complex-conditional-logic)

```
$template = [
    '@djson match userType',
    '@djson case admin',
    'permissions' => ['read', 'write', 'delete'],
    '@djson case editor',
    'permissions' => ['read', 'write'],
    '@djson case viewer',
    'permissions' => ['read'],
    '@djson default',
    'permissions' => []
];
```

For more examples, visit [djson.dev/examples](https://djson.dev)

Testing
-------

[](#testing)

DJson has comprehensive test coverage with 100% mutation score:

```
composer install
./vendor/bin/phpunit
```

**Test Results:**

- ✅ 103 tests, 385 assertions
- 🏆 100% mutation score (70/70 meaningful mutations killed)
- ⚡ Rock-solid quality assurance

API Reference
-------------

[](#api-reference)

### Core Methods

[](#core-methods)

```
// Process array/JSON template, return array
$result = $djson->process($template, $data);

// Process and return JSON string
$json = $djson->processToJson($template, $data, JSON_PRETTY_PRINT);

// Load from file, return array
$result = $djson->processFile('template.json', $data);

// Load from file, return JSON string
$json = $djson->processFileToJson('template.json', $data, JSON_PRETTY_PRINT);

// Validate template (returns array of errors, empty if valid)
$errors = $djson->validate($template);
```

### Directives

[](#directives)

DirectiveDescriptionExample`@djson for  as `Loop over array`@djson for users as user``@djson if `Include if truthy`@djson if isActive``@djson unless `Include if falsy`@djson unless isDeleted``@djson exists `Include if path exists`@djson exists user.email``@djson else`Else clause`@djson else``@djson match `Pattern matching`@djson match status``@djson case `Match case`@djson case active``@djson default`Default case`@djson default``@djson set  = `Set variable`@djson set total = price * qty``{{variable}}`Variable interpolation`{{user.name}}``{{var | function}}`Apply function`{{name | upper}}`### Loop Variables

[](#loop-variables)

- `{{_index}}` - Current loop index (0-based)
- `{{_key}}` - Current loop key
- `{{_first}}` - `true` if first iteration
- `{{_last}}` - `true` if last iteration

Requirements
------------

[](#requirements)

- PHP 8.1 or higher

Documentation
-------------

[](#documentation)

Complete documentation available at **[djson.dev](https://djson.dev)**:

- [Getting Started](https://djson.dev/getting-started)
- [Template Functions](https://djson.dev/functions)
- [Advanced Examples](https://djson.dev/examples)
- [API Reference](https://djson.dev/api)

License
-------

[](#license)

MIT

Author
------

[](#author)

**Qoliber** -

---

Made with ❤️ by [Qoliber](https://qoliber.com) | [Documentation](https://djson.dev) | [GitHub](https://github.com/qoliber/djson)

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance69

Regular maintenance activity

Popularity26

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

6

Last Release

181d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e1127b1eba3c8b9dce8b6f329f14afb6af88aafa8f1e08aac8f23f97ec8f68b5?d=identicon)[qoliber](/maintainers/qoliber)

---

Top Contributors

[![jakwinkler](https://avatars.githubusercontent.com/u/4256191?v=4)](https://github.com/jakwinkler "jakwinkler (8 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/qoliber-djson/health.svg)

```
[![Health](https://phpackages.com/badges/qoliber-djson/health.svg)](https://phpackages.com/packages/qoliber-djson)
```

###  Alternatives

[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[whitecube/nova-flexible-content

Flexible Content &amp; Repeater Fields for Laravel Nova.

8053.0M25](/packages/whitecube-nova-flexible-content)[mopa/bootstrap-bundle

Easy integration of twitters bootstrap into symfony2

7042.9M33](/packages/mopa-bootstrap-bundle)[limenius/react-bundle

Client and Server-side react rendering in a Symfony Bundle

3871.2M](/packages/limenius-react-bundle)[nicmart/string-template

StringTemplate is a very simple string template engine for php. I've written it to have a thing like sprintf, but with named and nested substutions.

2101.7M30](/packages/nicmart-string-template)[symfony/ux-icons

Renders local and remote SVG icons in your Twig templates.

555.8M69](/packages/symfony-ux-icons)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
