PHPackages                             bluem/javascript-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. bluem/javascript-serializer

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

bluem/javascript-serializer
===========================

Dependency-free serialization of PHP data to a JavaScript representation

1.1(7y ago)33.3kMITPHPPHP &gt;=7.0.0

Since May 4Pushed 7y ago1 watchersCompare

[ Source](https://github.com/BlueM/PHP-JavaScript-Serializer)[ Packagist](https://packagist.org/packages/bluem/javascript-serializer)[ RSS](/packages/bluem-javascript-serializer/feed)WikiDiscussions master Synced 4d ago

READMEChangelogDependencies (1)Versions (4)Used By (0)

[![Build Status](https://camo.githubusercontent.com/32be3f49fa0769634b453452623f9cf6b53be1f1466e4160bdde9a6dfb5a1f2b/68747470733a2f2f6170692e7472617669732d63692e6f72672f426c75654d2f5048502d4a6176615363726970742d53657269616c697a65722e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/BlueM/PHP-JavaScript-Serializer)[![SensioLabsInsight](https://camo.githubusercontent.com/42b2559d1d472771ec591daa1500e79ccf22160d6d264dfbf3ba415d0ab3fae3/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f61326132343031612d393036652d346639642d623838392d3431363839306136323063612f6d696e692e706e67)](https://insight.sensiolabs.com/projects/a2a2401a-906e-4f9d-b889-416890a620ca)

Overview
========

[](#overview)

This library provides a simple, dependency-free serialization of a PHP variable value / datastructure to strings which can be interpreted as a JavaScript value.

The most typical use case will be the automated generation of JavaScript code in cases where the amount of data is notably and therefore serializing to JSON would suffer from the deserialization penalty and/or the larger size of JSON data.

While I would have expected there are already some simililar libraries on packagist.org, I did not find any that are *not* bound to a specific use case, dataset or framework. If I missed something, please do not hesitate to contact me.

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

[](#installation)

Add `"bluem/javascript-serializer": "^1.0"` to the requirements in your `composer.json` file or run `composer require "bluem/javascript-serializer"` at the shell.

As this library uses [semantic versioning](https://semver.org), you will get fixes and feature additions when running `composer update`, but not changes which break the API.

Usage
-----

[](#usage)

Instantiate the class, call the `serialize()` method with any variable and use the return type. That’s it.

```
$jss = new \BlueM\JavaScriptSerializer();
$result = $jss->serialize($myVariable);

```

The following datatypes can be handled:

- `null`
- `string`
- `float`
- `int`
- `array`
- `\DateTime` (converted to a JavaScript `Date` constructor call)
- `object` – if the object implements the `\JsonSerializable` interface, has a public `toArray` method or has a public `__toString` method. (The mentioned order is exactly the order in which the code performs the checks.)

Examples
--------

[](#examples)

**Example 1:** Scalar PHP value

Input PHP data:

```
$var = 'Hello world';

```

Value returned from `$serializer->serialize($var)` call will be this string:

```
'Hello world'

```

**Example 2:** Array with numeric keys

Input PHP data:

```
$var = ['A', 'B', 3.14, 4711];

```

Value returned from `$serializer->serialize($var)` call will be this string:

```
['A', 'B', 3.14, 4711]

```

**Example 3:** Nested array

Input PHP data:

```
[
    'foo'    => 'bar',
    'nested' => [
        'pi'     => 3.14,
        'key'    => null,
        'abc'    => "String \" with 'quotes'",
        'My key' => 'Hello world',
        'bar'    => [
            'key'  => 'A',
            'code' => 65,
        ],
    ]
]

```

Value returned from `$serializer->serialize($var)` call will be this string:

```
{foo: 'bar', nested: {pi: 3.14, key: null, abc: 'String " with \'quotes\'', 'My key': 'Hello world', bar: {key: 'A', code: 65}}}

```

Known issues
------------

[](#known-issues)

- When creating object properties, strings that can be used as properties without quotes are inserted verbatim, without quotes. However, this decision is based on a very simple RegEx, which not only ignores the existence of ECMAScript 2015 Symbols, but also [other property names that can be used without quotes](https://mothereff.in/js-properties#12e34). This has no influence on using the code in JavaScript, but only on the code size. But chances are you will use some sort of minification, so this should not be a problem.

ToDo
----

[](#todo)

- In addition to the current, compact format, a “pretty-print” format should be choosable.

Version History
===============

[](#version-history)

1.1, 2019-03-28
---------------

[](#11-2019-03-28)

- Native PHP `\DateTime` instances are converted to native JavaScript `Date` constructor calls

1.0.1, 2017-10-14
-----------------

[](#101-2017-10-14)

- Improve exception message (explicitly mention class name) when object is not serializable.
- Improve doc comments and Readme.

1.0, 2017-05-04
---------------

[](#10-2017-05-04)

- First public version. Nothing else to say.

Author &amp; License
====================

[](#author--license)

This code was written by Carsten Blüm ([www.bluem.net](http://www.bluem.net)) and licensed under the BSD 2-Clause license.

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity60

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

Total

3

Last Release

2606d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1493457?v=4)[Carsten Blüm](/maintainers/BlueM)[@BlueM](https://github.com/BlueM)

---

Top Contributors

[![BlueM](https://avatars.githubusercontent.com/u/1493457?v=4)](https://github.com/BlueM "BlueM (14 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/bluem-javascript-serializer/health.svg)

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

###  Alternatives

[mtdowling/jmespath.php

Declaratively specify how to extract elements from a JSON document

2.0k472.8M135](/packages/mtdowling-jmespathphp)[opis/closure

A library that can be used to serialize closures (anonymous functions) and arbitrary data.

2.6k230.0M284](/packages/opis-closure)[masterminds/html5

An HTML5 parser and serializer.

1.8k242.8M229](/packages/masterminds-html5)[sabberworm/php-css-parser

Parser for CSS Files written in PHP

1.8k191.2M65](/packages/sabberworm-php-css-parser)[michelf/php-markdown

PHP Markdown

3.5k52.4M345](/packages/michelf-php-markdown)[jms/metadata

Class/method/property metadata management in PHP

1.8k152.8M88](/packages/jms-metadata)

PHPackages © 2026

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