PHPackages                             dotink/json - 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. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. dotink/json

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

dotink/json
===========

Better JSON Serialization for PHP

1.6.0(2y ago)39.1k↓72.6%11MITPHPCI failing

Since Nov 25Pushed 2y ago2 watchersCompare

[ Source](https://github.com/dotink/json)[ Packagist](https://packagist.org/packages/dotink/json)[ RSS](/packages/dotink-json/feed)WikiDiscussions master Synced 2d ago

READMEChangelogDependencies (3)Versions (12)Used By (1)

Think of this library as a way to move your `jsonSerialize()` method to a separate class that can be dependency injected, access protected/private properties and methods on their parent classes, and more.

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

[](#installation)

```
composer require dotink/json

```

Usage
-----

[](#usage)

```
$json = Json\Serialize($data);
```

The above function will prepare your `$data` using available normalizers registered in the `Json\Normalizer` namespace (by default). For example, if your `$data` is an array it will use the `Json\Normalizer\_Array` normalizer which will, in turn, normalize all the elements of the array.

### Object Normalization

[](#object-normalization)

Normalizing objects operates quite a bit differently.

Which normalizer is used depends on whether or not there is a corresponding normalizer available in the `Json\Normalizer` namespace (by default). If no corresponding normalizer can be found, it will revert to `Json\Normalizer\_Object` which will normalize all public properties.

For example, included in this library is a `Json\Normalizer\DateTime` class:

```
namespace Json\Normalizer;

class DateTime extends \Json\Normalizer
{
	public function jsonSerialize()
	{
		return $this->format('c');
	}
}
```

So if your object is of the class `DateTime`, it will use that normalizer.

Compare, for example:

```
Json\Serialize(new DateTime('today'))
```

Which outputs:

```
"2019-11-25T00:00:00-08:00"
```

To:

```
json_encode(new DateTime('today'))
```

Which outputs:

```
"{"date":"2019-11-25 00:00:00.000000","timezone_type":3,"timezone":"America\/Los_Angeles"}"
```

### Adding Normalizers

[](#adding-normalizers)

To add a custom object normalizer, simply create a new normalizer whose full class name (includes namespace) is prefixed by `Json\Normalizer`. If you want to normalize `My\Library\Acme` you would create `Json\Normalizer\My\Library\Acme`:

```
namespace Json\Normalizer\My\Library;

class Acme extends \Json\Normalizer
{
	public function jsonSerialize()
	{
		//
		// return normalized object
		//
	}
}
```

### What If I Don't Want to Use This Libraries Existing Normalizers?

[](#what-if-i-dont-want-to-use-this-libraries-existing-normalizers)

You can change the namespace in which normalizers are looked for:

```
Json\Normalizer::setNamespace('My\Json\Normalizer')
```

### What If I Need Additional Dependencies to Normalize My Objects?

[](#what-if-i-need-additional-dependencies-to-normalize-my-objects)

You can register any PSR-11 compatible container to resolve/construct your normalizers:

```
Json\Normalizer::setContainer($container);
```

### What If I Need To Normalize My Object Differently If It's Nested In Another Object?

[](#what-if-i-need-to-normalize-my-object-differently-if-its-nested-in-another-object)

You can determine whether or not the normalizer is nested using `$this('nested')`:

```
namespace Json\Normalizer\My\Library;

class Acme extends \Json\Normalizer
{
	public function jsonSerialize()
	{
		if ($this('nested')) {

			//
			// Return nested object's normalization
			//

		} else {

			//
			// Return non-nested object's normalization
			//

		}
	}
}
```

### What If I Need To Access Protected/Private Properties/Methods When Normalizing My Objects?

[](#what-if-i-need-to-access-protectedprivate-propertiesmethods-when-normalizing-my-objects)

Normalizers proxy all instance property/method calls to the underlying object and will use reflection to access the data/method if it's not accessible, so calling `$this->protectedProperty` or `$this->privateMethod()` will work as if the normalizer's `jsonSerialize()` method was on the class itself.

### Will Child Classes Be Using the Parent's Normalizer?

[](#will-child-classes-be-using-the-parents-normalizer)

Yes. Using the previous example `My\Library\AcmeChild` which extends `My\Library\Acme` would use `Json\Normalizer\My\Library\Acme` unless there was a `Json\Normalizer\My\Library\AcmeChild`.

### Will My Existing `JsonSerializable` Objects Be Normalized?

[](#will-my-existing-jsonserializable-objects-be-normalized)

Yes. If your object implements `JsonSerializable` there is a `Json\Normalizer\JsonSerializable` normalizer which will normalize the return value of that method.

### What If I Need to Normalize Objects With the Standard `json_encode()`?

[](#what-if-i-need-to-normalize-objects-with-the-standard-json_encode)

You can add custom normalization for objects regardless of whether or not they are encoded via `Json\Serialize()` or `json_encode()` by using the `Json\Serialize` trait:

```
class Acme implements Json\Serializable
{
	use Json\Serialize;
}
```

> NOTE: `Json\Serializable` is just a concrete stand-in interface for PHP's built-in `JsonSerializable`. If your object already implements `JsonSerializable` move the existing `jsonSerialize()` method to a custom normalizer.

### What If I Just Want to Normalize All Accessible Properties?

[](#what-if-i-just-want-to-normalize-all-accessible-properties)

You can use `Json\SerializeAllProperties` on your class instead of `Json\Serialize`:

```
class Acme implements Json\Serializable
{
	use Json\SerializeAllProperties;
}
```

### What If I Have Super-Secret Properties That Shouldn't Be Normalized... Starting with `_`?

[](#what-if-i-have-super-secret-properties-that-shouldnt-be-normalized-starting-with-_)

You can use `Json\SerializeStandardProperties` on your class instead of `Json\SerializeAllProperties`:

```
class Acme implements Json\Serializable
{
	use Json\SerializeStandardProperties;
}
```

### What If I Want To Normalize All Strings As "I'm a teapot?"

[](#what-if-i-want-to-normalize-all-strings-as-im-a-teapot)

You can add the following class and make it autoloadable:

```
namespace Json\Normalizer;

class _String extends \Json\Normalizer
{
	public function jsonSerialize()
	{
		return "I'm a teapot";
	}
}
```

### What If I Want To Serialize To XML?

[](#what-if-i-want-to-serialize-to-xml)

GTFO.

Caveats
-------

[](#caveats)

Normalization works by implementing `JsonSerializable` and wrapping data in normalizers that implement it. Since it is not possible to modify an built-in PHP class such as `DateTime` to directly implement `JsonSerializable` then encoding built-in PHP objects can produce different results using `Json\Serialize` and `json_encode()`.

It is, of course, possible to extend these objects and use `Json\Serialize`, but you will need to replace instantiation of such with the child class:

```
namespace My;

class DateTime extends \DateTime implements Json\Serializable
{
	use Json\Serialize;
}
```

Why Does This Exist?
--------------------

[](#why-does-this-exist)

The traditional PHP `json_encode()` function is capable of providing classes/objects a mechanism with which they can normalize their data to be serialized. The mechanism that does this is the `JsonSerializable` interface and the corresponding `jsonSerialize()` method. While this approach solves many basic cases of normalization, it does not solve many more advanced cases.

This library was written to solve a specific case wherein:

1. I needed a way to have standard `json_encode` serialize objects.
2. What data was serialized for those objects depended on if they were nested or not.
3. The normalization of data needed to be performed with additional dependencies which could not be injected into the objects, and probably shouldn't be just for the sake of their self-normalization.

### Why Not Use a Totally Separate Serialization Library?

[](#why-not-use-a-totally-separate-serialization-library)

While there are many great serialization libraries available, getting a serialization library into every place where `json_encode` might be used currently is not a realistic option. Additionally, without any sort of standard serialization interface, other libraries will likely still continue to use `json_encode()`. See point #1.

###  Health Score

34

—

LowBetter than 75% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity28

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity64

Established project with proven stability

 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 ~144 days

Recently: every ~4 days

Total

11

Last Release

970d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4ab2b91daf2aa6e4c7f98f785a3135daa3e9998bd7021d89df05a374e28ecde5?d=identicon)[mattsah](/maintainers/mattsah)

---

Top Contributors

[![mattsah](https://avatars.githubusercontent.com/u/586346?v=4)](https://github.com/mattsah "mattsah (24 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/dotink-json/health.svg)

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

###  Alternatives

[symfony/symfony

The Symfony PHP framework

31.4k87.2M2.2k](/packages/symfony-symfony)[symfony/dependency-injection

Allows you to standardize and centralize the way objects are constructed in your application

4.2k455.6M9.6k](/packages/symfony-dependency-injection)[api-platform/core

Build a fully-featured hypermedia or GraphQL API in minutes!

2.6k51.2M339](/packages/api-platform-core)[wikimedia/parsoid

Parsoid, a bidirectional parser between wikitext and HTML5

187557.3k3](/packages/wikimedia-parsoid)[moonshine/moonshine

Laravel administration panel

1.3k253.1k81](/packages/moonshine-moonshine)[ecotone/ecotone

Enterprise architecture layer for Laravel and Symfony — CQRS, Event Sourcing, Durable Workflows (Sagas, Orchestrators), Projections, and Outbox messaging via PHP attributes.

564576.7k53](/packages/ecotone-ecotone)

PHPackages © 2026

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