PHPackages                             nilportugues/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. [API Development](/categories/api)
4. /
5. nilportugues/json

ActiveLibrary[API Development](/categories/api)

nilportugues/json
=================

JSON transformer outputting valid API responses.

2.0.1(9y ago)564412MITPHPPHP &gt;=5.5.0

Since Aug 16Pushed 9y agoCompare

[ Source](https://github.com/nilportugues/php-json)[ Packagist](https://packagist.org/packages/nilportugues/json)[ Docs](http://nilportugues.com)[ RSS](/packages/nilportugues-json/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (7)Dependencies (3)Versions (8)Used By (2)

JSON Transformer
================

[](#json-transformer)

\[[![Build Status](https://camo.githubusercontent.com/5223ecac0e7d45d16f6b6fecbdc860e18115c532a51b5beaab77f167c48860b9/68747470733a2f2f7472617669732d63692e6f72672f6e696c706f727475677565732f7068702d6a736f6e2e737667)](https://camo.githubusercontent.com/5223ecac0e7d45d16f6b6fecbdc860e18115c532a51b5beaab77f167c48860b9/68747470733a2f2f7472617669732d63692e6f72672f6e696c706f727475677565732f7068702d6a736f6e2e737667)\] () \[[![Coverage Status](https://camo.githubusercontent.com/41548f73dbe359325b37815b36eca005abf8209f5bede7a4286cfe2b63575303/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6e696c706f727475677565732f6a736f6e2d7472616e73666f726d65722f62616467652e7376673f6272616e63683d6d617374657226736572766963653d676974687562)](https://camo.githubusercontent.com/41548f73dbe359325b37815b36eca005abf8209f5bede7a4286cfe2b63575303/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6e696c706f727475677565732f6a736f6e2d7472616e73666f726d65722f62616467652e7376673f6272616e63683d6d617374657226736572766963653d676974687562)\] () \[[![Scrutinizer Code Quality](https://camo.githubusercontent.com/d9d5b567a3074252f4b32636e8e7449842582e53bd0a62666bc6ef0d036a89e2/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e696c706f727475677565732f6a736f6e2d7472616e73666f726d65722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://camo.githubusercontent.com/d9d5b567a3074252f4b32636e8e7449842582e53bd0a62666bc6ef0d036a89e2/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e696c706f727475677565732f6a736f6e2d7472616e73666f726d65722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)\] () \[[![SensioLabsInsight](https://camo.githubusercontent.com/b178155bc81d9721e57ed2a9bb19987cf1ddf5d4ddc20e1f56d4e812e794aab0/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f37366630323166612d363535392d346661662d613031302d3564666239356364373065322f6d696e692e706e67)](https://camo.githubusercontent.com/b178155bc81d9721e57ed2a9bb19987cf1ddf5d4ddc20e1f56d4e812e794aab0/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f37366630323166612d363535392d346661662d613031302d3564666239356364373065322f6d696e692e706e67)\] () \[[![Latest Stable Version](https://camo.githubusercontent.com/7a9f96c63e5eca3f1815b94a47920319b7aa8d6da8345209851242d36557b692/68747470733a2f2f706f7365722e707567782e6f72672f6e696c706f727475677565732f6a736f6e2f762f737461626c65)](https://camo.githubusercontent.com/7a9f96c63e5eca3f1815b94a47920319b7aa8d6da8345209851242d36557b692/68747470733a2f2f706f7365722e707567782e6f72672f6e696c706f727475677565732f6a736f6e2f762f737461626c65)\] () \[[![Total Downloads](https://camo.githubusercontent.com/288f02202260704d1ff6bfb5c6d221078c5e20f7a3061e10e875bc4db9f9efc6/68747470733a2f2f706f7365722e707567782e6f72672f6e696c706f727475677565732f6a736f6e2f646f776e6c6f616473)](https://camo.githubusercontent.com/288f02202260704d1ff6bfb5c6d221078c5e20f7a3061e10e875bc4db9f9efc6/68747470733a2f2f706f7365722e707567782e6f72672f6e696c706f727475677565732f6a736f6e2f646f776e6c6f616473)\] () \[[![License](https://camo.githubusercontent.com/d6d85a3bb4fac95639b1b23af449ffcfc66a2cc1f4ea4f47d4a61a1f476a7d66/68747470733a2f2f706f7365722e707567782e6f72672f6e696c706f727475677565732f6a736f6e2f6c6963656e7365)](https://camo.githubusercontent.com/d6d85a3bb4fac95639b1b23af449ffcfc66a2cc1f4ea4f47d4a61a1f476a7d66/68747470733a2f2f706f7365722e707567782e6f72672f6e696c706f727475677565732f6a736f6e2f6c6963656e7365)\] () [![Donate](https://camo.githubusercontent.com/7b6de155df30b37b25eb5fec52f9213680c3dbf067dfb7d7e2850ac4096c7d05/68747470733a2f2f7777772e70617970616c6f626a656374732e636f6d2f656e5f55532f692f62746e2f62746e5f646f6e6174655f534d2e676966)](https://paypal.me/nilportugues)

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

[](#installation)

Use [Composer](https://getcomposer.org) to install the package:

```
$ composer require nilportugues/json
```

Usage
-----

[](#usage)

Given a PHP Object, and a series of mappings, the **JSON Transformer** will represent the given data as a JSON object.

For instance, given the following piece of code, defining a Blog Post and some comments:

```
$post = new Post(
  new PostId(9),
  'Hello World',
  'Your first post',
  new User(
      new UserId(1),
      'Post Author'
  ),
  [
      new Comment(
          new CommentId(1000),
          'Have no fear, sers, your king is safe.',
          new User(new UserId(2), 'Barristan Selmy'),
          [
              'created_at' => (new DateTime('2015/07/18 12:13:00'))->format('c'),
              'accepted_at' => (new DateTime('2015/07/19 00:00:00'))->format('c'),
          ]
      ),
  ]
);
```

And a Mapping array for all the involved classes:

```
use NilPortugues\Api\Mapping\Mapper;

$mappings = [
    [
        'class' => Post::class,
        'alias' => 'Message',
        'aliased_properties' => [
            'author' => 'author',
            'title' => 'headline',
            'content' => 'body',
        ],
        'hide_properties' => [

        ],
        'id_properties' => [
            'postId',
        ],
        'urls' => [
            'self' => 'http://example.com/posts/{postId}',
            'comments' => 'http://example.com/posts/{postId}/comments'
        ],
    ],
    [
        'class' => PostId::class,
        'alias' => '',
        'aliased_properties' => [],
        'hide_properties' => [],
        'id_properties' => [
            'postId',
        ],
        'urls' => [
            'self' => 'http://example.com/posts/{postId}',
        ],
    ],
    [
        'class' => User::class,
        'alias' => '',
        'aliased_properties' => [],
        'hide_properties' => [],
        'id_properties' => [
            'userId',
        ],
        'urls' => [
            'self' => 'http://example.com/users/{userId}',
            'friends' => 'http://example.com/users/{userId}/friends',
            'comments' => 'http://example.com/users/{userId}/comments',
        ],
    ],
    [
        'class' => UserId::class,
        'alias' => '',
        'aliased_properties' => [],
        'hide_properties' => [],
        'id_properties' => [
            'userId',
        ],
        'urls' => [
            'self' => 'http://example.com/users/{userId}',
            'friends' => 'http://example.com/users/{userId}/friends',
            'comments' => 'http://example.com/users/{userId}/comments',
        ],
    ],
    [
        'class' => Comment::class,
        'alias' => '',
        'aliased_properties' => [],
        'hide_properties' => [],
        'id_properties' => [
            'commentId',
        ],
        'urls' => [
            'self' => 'http://example.com/comments/{commentId}',
        ],
    ],
    [
        'class' => CommentId::class,
        'alias' => '',
        'aliased_properties' => [],
        'hide_properties' => [],
        'id_properties' => [
            'commentId',
        ],
        'urls' => [
            'self' => 'http://example.com/comments/{commentId}',
        ],
    ],
];

$mapper = new Mapper($mappings);
```

Calling the transformer will output a **valid JSON response** using the correct formatting:

```
use NilPortugues\Api\Json\JsonSerializer;
use NilPortugues\Api\Json\Http\Message\Response;

$serializer = new JsonSerializer($mapper);
$output = $serializer->serialize($post);

//PSR7 Response with headers and content.
$response = new Response($output);

header(
    sprintf(
        'HTTP/%s %s %s',
        $response->getProtocolVersion(),
        $response->getStatusCode(),
        $response->getReasonPhrase()
    )
);
foreach($response->getHeaders() as $header => $values) {
    header(sprintf("%s:%s\n", $header, implode(', ', $values)));
}

echo $response->getBody();
```

**Output:**

```
HTTP/1.1 200 OK
Cache-Control: private, max-age=0, must-revalidate
Content-type: application/json; charset=utf-8

```

```
{
  "post_id": 9,
  "headline": "Hello World",
  "body": "Your first post",
  "author": {
    "user_id": 1,
    "name": "Post Author"
  },
  "comments": [
    {
      "comment_id": 1000,
      "dates": {
        "created_at": "2015-07-18T12:13:00+02:00",
        "accepted_at": "2015-07-19T00:00:00+02:00"
      },
      "comment": "Have no fear, sers, your king is safe.",
      "user": {
        "user_id": 2,
        "name": "Barristan Selmy"
      }
    }
  ],
  "links": {
    "self": {
      "href": "http://example.com/posts/9"
    },
    "comments": {
      "href": "http://example.com/posts/9/comments"
    }
  }
}
```

Quality
-------

[](#quality)

To run the PHPUnit tests at the command line, go to the tests directory and issue phpunit.

This library attempts to comply with [PSR-1](http://www.php-fig.org/psr/psr-1/), [PSR-2](http://www.php-fig.org/psr/psr-2/), [PSR-4](http://www.php-fig.org/psr/psr-4/) and [PSR-7](http://www.php-fig.org/psr/psr-7/).

If you notice compliance oversights, please send a patch via [Pull Request](https://github.com/nilportugues/json-transformer/pulls).

Contribute
----------

[](#contribute)

Contributions to the package are always welcome!

- Report any bugs or issues you find on the [issue tracker](https://github.com/nilportugues/json-transformer/issues/new).
- You can grab the source code at the package's [Git repository](https://github.com/nilportugues/json-transformer).

Support
-------

[](#support)

Get in touch with me using one of the following means:

- Emailing me at
- Opening an [Issue](https://github.com/nilportugues/json-transformer/issues/new)
- Using Gitter: [![Gitter](https://camo.githubusercontent.com/abe08b740a4156153736f791393ec4da6619c4be73212e75769f52edacc0e2b5/68747470733a2f2f6261646765732e6769747465722e696d2f4a6f696e253230436861742e737667)](https://gitter.im/nilportugues/json-transformer?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)

Authors
-------

[](#authors)

- [Nil Portugués Calderó](http://nilportugues.com)
- [The Community Contributors](https://github.com/nilportugues/json-transformer/graphs/contributors)

License
-------

[](#license)

The code base is licensed under the [MIT license](LICENSE).

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity19

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 97.4% 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 ~51 days

Recently: every ~61 days

Total

7

Last Release

3623d ago

Major Versions

1.0.4 → 2.0.02016-06-16

### Community

Maintainers

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

---

Top Contributors

[![nilportugues](https://avatars.githubusercontent.com/u/550948?v=4)](https://github.com/nilportugues "nilportugues (37 commits)")[![lferro9000](https://avatars.githubusercontent.com/u/2652260?v=4)](https://github.com/lferro9000 "lferro9000 (1 commits)")

---

Tags

apijsonjson-apijson-transformationjsonapimarshallermicroservicemicroservicesphpphp7serializertransformerresponsejsonapipsr7serializertransformer

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

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

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

###  Alternatives

[nilportugues/json-api

Serializer transformers outputting valid API responses in JSON, JSON API and HAL+JSON API formats.

70106.2k3](/packages/nilportugues-json-api)[nilportugues/laravel5-json-api

Laravel 5 JSON API Transformer Package

31232.4k1](/packages/nilportugues-laravel5-json-api)[nilportugues/jsonapi-bundle

Symfony 2 &amp; 3 JSON API Transformer Package

11446.0k](/packages/nilportugues-jsonapi-bundle)[nilportugues/hal

HAL+JSON &amp; HAL+XML API transformer outputting valid API responses.

317.7k2](/packages/nilportugues-hal)[nilportugues/laravel5-json-api-dingo

Laravel5 JSONAPI and Dingo together to build APIs fast

311.5k](/packages/nilportugues-laravel5-json-api-dingo)[nilportugues/api-problems

PSR7 Response implementation for the Problem Details for HTTP APIs

1749.4k2](/packages/nilportugues-api-problems)

PHPackages © 2026

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