PHPackages                             zumba/json-serializer - 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. zumba/json-serializer

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

zumba/json-serializer
=====================

Serialize PHP variables, including objects, in JSON format. Support to unserialize it too.

3.2.4(3mo ago)129770.3k↓46%25[5 issues](https://github.com/zumba/json-serializer/issues)14MITPHPPHP ^7.2 || ^8.0CI passing

Since Jan 6Pushed 2mo ago14 watchersCompare

[ Source](https://github.com/zumba/json-serializer)[ Packagist](https://packagist.org/packages/zumba/json-serializer)[ Docs](https://tech.zumba.com)[ RSS](/packages/zumba-json-serializer/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (10)Dependencies (2)Versions (21)Used By (14)Security (1)

Json Serializer for PHP
=======================

[](#json-serializer-for-php)

 [ ![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265) ](LICENSE.txt) [![Build Status](https://github.com/zumba/json-serializer/actions/workflows/php.yml/badge.svg?branch=master)](https://github.com/zumba/json-serializer/actions/workflows/php.yml/badge.svg?branch=master) [ ![Total Downloads](https://camo.githubusercontent.com/38d9af151b71113e086f3778236108481cb37eb13ebb81be070025750b21eb31/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7a756d62612f6a736f6e2d73657269616c697a65722e7376673f7374796c653d666c61742d737175617265) ](https://packagist.org/packages/zumba/json-serializer) [ ![Latest Stable Version](https://camo.githubusercontent.com/56e5604dc83b308f1c66eb783170191f7e5a1d89d9d654ba739f82ea8734ca30/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7a756d62612f6a736f6e2d73657269616c697a65722e7376673f7374796c653d666c61742d737175617265266c6162656c3d737461626c65) ](https://packagist.org/packages/zumba/json-serializer)

This is a library to serialize PHP variables in JSON format. It is similar of the `serialize()` function in PHP, but the output is a string JSON encoded. You can also unserialize the JSON generated by this tool and have you PHP content back.

Supported features:

- Encode/Decode of scalar, null, array
- Encode/Decode of objects
- Encode/Decode of binary data
- Support nested serialization
- Support not declared properties on the original class definition (ie, properties in `stdClass`)
- Support object recursion
- Closures (via 3rd party library. See details below)

Unsupported serialization content:

- Resource (ie, `fopen()` response)
- NAN, INF constants

Limitations:

- Binary data containing null bytes (\\u0000) as array keys cannot be properly decoded because of a json extension bug:
    - [remicollet/pecl-json-c#7](https://github.com/remicollet/pecl-json-c/issues/7)
    - [json-c/json-c#108](https://github.com/json-c/json-c/issues/108)

This project should not be confused with `JsonSerializable` interface added on PHP 5.4. This interface is used on `json_encode` to encode the objects. There is no unserialization with this interface, differently from this project.

*Json Serializer requires PHP &gt;= 7.2 and tested until PHP 8.4*

Security: do not unserialize untrusted input
--------------------------------------------

[](#security-do-not-unserialize-untrusted-input)

> **Warning**Never pass untrusted data (user input, third-party API responses, cookies, etc.) to `unserialize()` without first restricting which classes may be instantiated.

The JSON format used by this library embeds a `@type` key that names the PHP class to restore. Without restrictions an attacker who controls the JSON payload can cause **any class available in the autoloader to be instantiated**, including classes whose `__wakeup()` or `__destruct()` methods execute dangerous operations (remote code execution, file deletion, etc.).

Use `setAllowedClasses()` to declare the exact set of classes your application expects to deserialize:

```
$serializer = new Zumba\JsonSerializer\JsonSerializer();
$serializer->setAllowedClasses([
    MyApp\Model\User::class,
    MyApp\Model\Order::class,
]);

// Safe: User and Order are allowed.
$obj = $serializer->unserialize($jsonFromDatabase);

// Throws JsonSerializerException: SomeOtherClass is not in the allowlist.
$obj = $serializer->unserialize($attackerControlledJson);
```

`setAllowedClasses()` accepts:

ValueBehaviour`null` *(default)*No restriction — any known class can be instantiated. Keep this only for fully trusted, internally-generated JSON.`[]` (empty array)All class instantiation is blocked.`['Foo', 'Bar']`Only `Foo` and `Bar` (exact class names) may be instantiated.Classes registered via the custom object serializer map are always allowed regardless of this setting, because they are explicitly configured by the developer.

Example
-------

[](#example)

```
class MyCustomClass {
	public $isItAwesome = true;
	protected $nice = 'very!';
}

$instance = new MyCustomClass();

$serializer = new Zumba\JsonSerializer\JsonSerializer();
$json = $serializer->serialize($instance);
// $json will contain the content {"@type":"MyCustomClass","isItAwesome":true,"nice":"very!"}

$serializer->setAllowedClasses([MyCustomClass::class]);
$restoredInstance = $serializer->unserialize($json);
// $restoredInstance will be an instance of MyCustomClass
```

How to Install
--------------

[](#how-to-install)

If you are using composer, install the package [`zumba/json-serializer`](https://packagist.org/packages/zumba/json-serializer).

```
$ composer require zumba/json-serializer

```

Or add the `zumba/json-serializer` directly in your `composer.json` file.

If you are not using composer, you can just copy the files from `src` folder in your project.

Serializing Binary Strings
--------------------------

[](#serializing-binary-strings)

Binary strings introduce two special identifiers in the final json: `@utf8encoded` and `@scalar`. `@utf8encoded` is an array of keys from the original data which have their value (or the keys themselves) encoded from 8bit to UTF-8. This is how the serializer knows what to encode back from UTF-8 to 8bit when deserializing. Example:

```
$data = ['key' => '', 'anotherkey' => 'nonbinaryvalue'];
$serializer = new Zumba\JsonSerializer\JsonSerializer();
$json = $serializer->serialize($data);
// $json will contain the content {"key":"","anotherkey":"nonbinaryvalue","@utf8encoded":{"key":1}}
```

`@scalar` is used only when the value to be encoded is not an array or an object but a binary string. Example:

```
$data = '';
$serializer = new Zumba\JsonSerializer\JsonSerializer();
$json = $serializer->serialize($data);
// $json will contain the content {"@scalar":"","@utf8encoded":1}
```

Serializing Closure
-------------------

[](#serializing-closure)

For serializing PHP closures you can either use [OpisClosure](https://github.com/opis/closure) (preferred) or [SuperClosure](https://github.com/jeremeamia/super_closure) (the project is abandoned, so kept here for backward compatibility).

Closure serialization has some limitations. Please check the OpisClosure or SuperClosure project to check if it fits your needs.

To use the OpisClosure with JsonSerializer, just add it to the closure serializer list. Example:

```
$toBeSerialized = [
	'data' => [1, 2, 3],
	'worker' => function ($data) {
		$double = [];
		foreach ($data as $i => $number) {
			$double[$i] = $number * 2;
		}
		return $double;
	}
];

$jsonSerializer = new \Zumba\JsonSerializer\JsonSerializer();
$jsonSerializer->addClosureSerializer(new \Zumba\JsonSerializer\ClosureSerializer\OpisClosureSerializer());
$serialized = $jsonSerializer->serialize($toBeSerialized);
```

You can load multiple closure serializers in case you are migrating from SuperClosure to OpisClosure for example.

PS: JsonSerializer does not have a hard dependency of OpisClosure or SuperClosure. If you want to use both projects make sure you add both on your composer requirements and load them with `addClosureSerializer()` method.

Custom Serializers
------------------

[](#custom-serializers)

Some classes may not be suited to be serialized and unserialized using the default reflection methods.

Custom serializers provide the ability to define `serialize` and `unserialize` methods for specific classes.

```
class MyType {
    public $field1;
    public $field2;
}

class MyTypeSerializer {
    public function serialize(MyType $obj) {
        return array('fields' => $obj->field1 . ' ' . $obj->field2);
    }

    public function unserialize($values) {
        list($field1, $field2) = explode(' ', $values['fields']);
        $obj = new MyType();
        $obj->field1 = $field1;
        $obj->field2 = $field2;
        return $obj;
    }
}

// map of "class name" => Custom serializer
$customObjectSerializers['MyType'] = new MyTypeSerializer();
$jsonSerializer = new Zumba\JsonSerializer\JsonSerializer(null, $customObjectSerializers);

$toBeSerialized = new MyType();
$toBeSerialized->field1 = 'x';
$toBeSerialized->field2 = 'y';
$json = $jsonSerializer->serialize($toBeSerialized);
// $json == {"@type":"Zumba\\\\JsonSerializer\\\\Test\\\\SupportClasses\\\\MyType","fields":"x y"}

$myType = $jsonSerializer->unserialize($json);
// $myType == $toBeSerialized
```

###  Health Score

66

—

FairBetter than 99% of packages

Maintenance83

Actively maintained with recent releases

Popularity54

Moderate usage in the ecosystem

Community37

Small or concentrated contributor base

Maturity77

Established project with proven stability

 Bus Factor1

Top contributor holds 67.1% 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 ~295 days

Recently: every ~219 days

Total

16

Last Release

110d ago

Major Versions

1.0.2 → 2.0.02016-02-29

2.2.0 → 3.0.02020-07-20

PHP version history (5 changes)1.0.0PHP &gt;=5.3.6

2.0.0PHP &gt;=5.4.0

3.0.0PHP &gt;=7.0.0

3.0.2PHP ^7.0 || ^8.0

3.2.2PHP ^7.2 || ^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/26548?v=4)[Juan Basso](/maintainers/jrbasso)[@jrbasso](https://github.com/jrbasso)

![](https://avatars.githubusercontent.com/u/157755?v=4)[Chris Saylor](/maintainers/cjsaylor)[@cjsaylor](https://github.com/cjsaylor)

![](https://avatars.githubusercontent.com/u/497048?v=4)[Stephen Young](/maintainers/young-steveo)[@young-steveo](https://github.com/young-steveo)

---

Top Contributors

[![jrbasso](https://avatars.githubusercontent.com/u/26548?v=4)](https://github.com/jrbasso "jrbasso (110 commits)")[![williamdes](https://avatars.githubusercontent.com/u/7784660?v=4)](https://github.com/williamdes "williamdes (18 commits)")[![Copilot](https://avatars.githubusercontent.com/in/1143301?v=4)](https://github.com/Copilot "Copilot (11 commits)")[![cjsaylor](https://avatars.githubusercontent.com/u/157755?v=4)](https://github.com/cjsaylor "cjsaylor (10 commits)")[![marcimat](https://avatars.githubusercontent.com/u/355431?v=4)](https://github.com/marcimat "marcimat (6 commits)")[![ghola](https://avatars.githubusercontent.com/u/932205?v=4)](https://github.com/ghola "ghola (2 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")[![MauricioFauth](https://avatars.githubusercontent.com/u/120970?v=4)](https://github.com/MauricioFauth "MauricioFauth (2 commits)")[![MaxGfeller](https://avatars.githubusercontent.com/u/361435?v=4)](https://github.com/MaxGfeller "MaxGfeller (1 commits)")[![przemyslaw-bogusz](https://avatars.githubusercontent.com/u/35422131?v=4)](https://github.com/przemyslaw-bogusz "przemyslaw-bogusz (1 commits)")[![aramonc](https://avatars.githubusercontent.com/u/2242224?v=4)](https://github.com/aramonc "aramonc (1 commits)")

---

Tags

jsonserializeserializer

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[laktak/hjson

JSON for Humans. A configuration file format with relaxed syntax, fewer mistakes and more comments.

86241.3k14](/packages/laktak-hjson)[thunderer/serializard

Flexible serializer

2667.7k1](/packages/thunderer-serializard)[pmjones/throwable-properties

Copies properties of a Throwable to a serializable object.

1556.8k2](/packages/pmjones-throwable-properties)

PHPackages © 2026

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