For a recent project, I had to generate JSON files in a sensible, structured, and extensible way.

In the course of doing so, I developed a neat bit of syntactic sugar that saved me lots of lines of code, and made my PHP a lot more readable.

The End

So here’s my neat little bit of syntactic sugar.

The Beginning

Why is this great? Because one might, for instance, want to generate a file like this:

The Middle

And now I can write this:

The larger my JSON Document gets, the even better this gets, because I can decompose parts of my Document into sensible sections, and replace them with other JsonThing objects as necessary.

(Immediate improvement: implement JsonSerializable and run validate() automatically in jsonSerialize().)

Alternate Versions

Ugly version 1

The quick n’ dirty way of doing this involves nested arrays.

The problem with this is that arrays aren’t objects. Objects are helpful because we can define required values, throw some validation in jsonSerialize() (if we’ve implemented JsonSerializable), and use extensibility in neat ways.

For example, I’d love to be able to do this:

Something like that, probably using __set() as well.

Ugly Version 2

The other way of doing this is do lots of objects.

Code geek. Board game geek. Coffee geek. Bible geek.

Code geek. Board game geek. Coffee geek. Bible geek.