PHPackages                             paulzi/yii2-json-behavior - 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. [Validation &amp; Sanitization](/categories/validation)
4. /
5. paulzi/yii2-json-behavior

ActiveYii2-extension[Validation &amp; Sanitization](/categories/validation)

paulzi/yii2-json-behavior
=========================

Yii2 json attribute behavior

v1.0.7(6y ago)76528.6k↓21.5%15[1 issues](https://github.com/paulzi/yii2-json-behavior/issues)[1 PRs](https://github.com/paulzi/yii2-json-behavior/pulls)3MITPHPPHP &gt;=5.4.0

Since Aug 17Pushed 2y ago7 watchersCompare

[ Source](https://github.com/paulzi/yii2-json-behavior)[ Packagist](https://packagist.org/packages/paulzi/yii2-json-behavior)[ RSS](/packages/paulzi-yii2-json-behavior/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (2)Versions (11)Used By (3)

Yii2 json attribute behavior
============================

[](#yii2-json-attribute-behavior)

Auto decode/encode attribute value in json, provide array access and json validator.

**WARNING! From version 2.0.14 Yii has built-in DB JSON-type, and this behavior is no longer required.**

[Russian readme](https://github.com/paulzi/yii2-json-behavior/blob/master/README.ru.md)

[![Packagist Version](https://camo.githubusercontent.com/9f5d71031cfa14ce9a62dc091213c2f0c01cfbf9f254af9d51aa5508c4ae7668/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7061756c7a692f796969322d6a736f6e2d6265686176696f722e737667)](https://packagist.org/packages/paulzi/yii2-json-behavior)[![Code Coverage](https://camo.githubusercontent.com/e7124a66c99e9d208493089781daebd3eb93bc3543fb5e52b938b5233f14ce6c/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f636f7665726167652f672f7061756c7a692f796969322d6a736f6e2d6265686176696f722f6d61737465722e737667)](https://scrutinizer-ci.com/g/paulzi/yii2-json-behavior/?branch=master)[![Scrutinizer](https://camo.githubusercontent.com/553af08a7c8378f4a78189a90a5e97e67c6115bb96dd014e5b6330bcbd0c5a36/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f7061756c7a692f796969322d6a736f6e2d6265686176696f722e737667)](https://scrutinizer-ci.com/g/paulzi/yii2-json-behavior/?branch=master)[![Build Status](https://camo.githubusercontent.com/11e3069fba8878b3df49520f0ce46fbc4579d01cb34093cf88e08a94aa5ddb07/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f7061756c7a692f796969322d6a736f6e2d6265686176696f722f6d61737465722e737667)](https://travis-ci.org/paulzi/yii2-json-behavior)[![Total Downloads](https://camo.githubusercontent.com/d866cce6e4e6a62dee327ca8ef51daefc13b6bdc7097ff67d6d31dbd2dbdac36/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7061756c7a692f796969322d6a736f6e2d6265686176696f722e737667)](https://packagist.org/packages/paulzi/yii2-json-behavior)

Install
-------

[](#install)

Install via Composer:

```
composer require paulzi/yii2-json-behavior
```

or add

```
"paulzi/yii2-json-behavior" : "~1.0.0"
```

to the `require` section of your `composer.json` file.

Usage
-----

[](#usage)

### JsonBehavior

[](#jsonbehavior)

Configure your model:

```
use paulzi\jsonBehavior\JsonBehavior;

class Item extends \yii\db\ActiveRecord
{
    public function behaviors() {
        return [
            [
                'class' => JsonBehavior::className(),
                'attributes' => ['params'],
            ],
        ];
    }
}
```

Now you can access to attribute as array:

```
$item = Item::findOne(1);
$item->params['one'] = 'two';
$item->params['two'] = [];
$item->params['two']['key'] = true;
$item->save();

$item = Item::findOne(1);
echo $item['two']['key']; // true
```

Set attribute via json string:

```
$item = new Item();
$item->params->set('[2, 4, 42]');
echo $item->params[2]; // 42
```

Set attribute via array:

```
$item = new Item();
$item->params->set(['test' => ['one' => 1]]);
echo $item->params['test']['one']; // 1
```

Convert to json string:

```
$item = new Item();
$item->params['test'] = ['one' => false, 'two' => [1, 2, 3]];
var_dump((string)$item->params); // {"one":false,"two":[1,2,3]}
```

Convert to array:

```
$item = new Item();
$item->params->set('{ "one": 1, "two": null, "three": false, "four": "four" }');
var_dump($item->params->toArray());
```

Check empty:

```
$item = new Item();
$item->params->set('{}');
var_dump($item->params->isEmpty()); // true
```

#### emptyValue

[](#emptyvalue)

You can set `emptyValue` option to define an empty JSON value (default `null`). Can be `'{}'`, `'[]''` or `null`.

### JsonValidator

[](#jsonvalidator)

Configure your model (see behavior config upper):

```
use paulzi\jsonBehavior\JsonValidator;

class Item extends \yii\db\ActiveRecord
{
    public function rules() {
        return [
            [['params'], JsonValidator::className()],
        ];
    }
}
```

Validate:

```
$item = new Item();
$item->attributes = ['params' => '{ test: }'];
var_dump($item->save()); // false
var_dump($item->errors); // ['params' => ['Value is not valid JSON or scalar']]
```

You can set `merge = true`, in this case, instead of replacing all field data of the transmitted data, `array_merge()` will be applied with old data in the field (which are taken from `oldAttributes` of ActiveRecord). This option can be apply only with ActiveRecord:

```
use paulzi\jsonBehavior\JsonValidator;

class Item extends \yii\db\ActiveRecord
{
    public function rules() {
        return [
            [['params'], JsonValidator::className(), 'merge' => true],
        ];
    }
}
```

### JsonField

[](#jsonfield)

You can use `JsonField` class for other models:

```
class Item
{
    public $params;

    public function __constructor()
    {
        $this->params = new JsonField();
    }
}

// ...

$item = new Item();
$item->params['one'] = 1;
var_dump((string)$item->params); // {"one":1}
```

How To
------

[](#how-to)

### Usage isAttributeChanged() and getDirtyAttributes()

[](#usage-isattributechanged-and-getdirtyattributes)

Yii2 does not provide the ability to inject code to check attribute dirty.

If you need to use methods `isAttributeChanged()` or `getDirtyAttributes()`, you can override them in model:

```
/**
 * @inheritdoc
 */
public function isAttributeChanged($name, $identical = true)
{
    if ($this->$name instanceof JsonField) {
        return (string)$this->$name !== $this->getOldAttribute($name);
    } else {
        return parent::isAttributeChanged($name, $identical);
    }
}

/**
 * @inheritdoc
 */
public function getDirtyAttributes($names = null)
{
    $result = [];
    $data = parent::getDirtyAttributes($names);
    foreach ($data as $name => $value) {
        if ($value instanceof JsonField) {
            if ((string)$value !== $this->getOldAttribute($name)) {
                $result[$name] = $value;
            }
        } else {
            $result[$name] = $value;
        }
    }
    return $result;
}
```

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity50

Moderate usage in the ecosystem

Community22

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 89.5% 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 ~188 days

Recently: every ~226 days

Total

8

Last Release

2244d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/9402208?v=4)[PaulZi](/maintainers/PaulZi)[@paulzi](https://github.com/paulzi)

---

Top Contributors

[![paulzi](https://avatars.githubusercontent.com/u/9402208?v=4)](https://github.com/paulzi "paulzi (17 commits)")[![Izumi-kun](https://avatars.githubusercontent.com/u/1062584?v=4)](https://github.com/Izumi-kun "Izumi-kun (1 commits)")[![ptheofan](https://avatars.githubusercontent.com/u/880939?v=4)](https://github.com/ptheofan "ptheofan (1 commits)")

---

Tags

jsonvalidatoryii2Behavior

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/paulzi-yii2-json-behavior/health.svg)

```
[![Health](https://phpackages.com/badges/paulzi-yii2-json-behavior/health.svg)](https://phpackages.com/packages/paulzi-yii2-json-behavior)
```

###  Alternatives

[arogachev/yii2-many-to-many

Many-to-many ActiveRecord relation for Yii 2 framework

3541.2k4](/packages/arogachev-yii2-many-to-many)[dstotijn/yii2-json-schema-validator

A Yii2 extension that provides a validator class for JSON Schema validation.

1730.7k](/packages/dstotijn-yii2-json-schema-validator)[codeonyii/yii2-at-least-validator

Validates at least one (or more) attributes.

28253.5k1](/packages/codeonyii-yii2-at-least-validator)[insolita/yii2-array-structure-validator

Validate array with complex structure

1326.4k2](/packages/insolita-yii2-array-structure-validator)

PHPackages © 2026

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