I am loving GitHub code review so much that people are suggesting that I should change my title to Comparer of Unmerged Neglectable Technicalities. Otherwise known as … nevermind.
Category: Programming
A big part of my work has to do with code. I’ve worked as system administrator – installing, patching, and configuring someone else’s code. I’ve worked as independent programmer, writing code on my own. I also programmed as part of the team. And on top of that, I worked as Team Leader and Project Manager, where I had to interact a lot with programmers. Programming world on its own is as huge as the universe. There is always something to learn. When I find something worthy or something that I understand enough to write about, I share it in this category.
Beautifying PHP’s json_encode() output
I’ve been working a bit more with PHP and JSON recently and one of the things that annoyed me quite a bit was the single line output of the json_encode() function. Here is an example:
<?php $data = array( 'foo' => 'bar', 'bar' => 'qux', 'blah' => 'blah', ); echo json_encode($data); ?>
Poorly readable result (imagine having larger, more complex data structures like nested arrays):
{"foo":"bar","bar":"qux","blah":"blah"}
Apparently, since PHP 5.4.0 it became much easier to optionally format the output with some indentation. json_encode() function has an $options parameter, which was given an extra option – JSON_PRETTY_PRINT. Here is an updated example:
<?php $data = array( 'foo' => 'bar', 'bar' => 'qux', 'blah' => 'blah', ); echo json_encode($data, JSON_PRETTY_PRINT); ?>
And an updated output:
{
"foo": "bar",
"bar": "qux",
"blah": "blah"
}
Very handy for debugging and for those bits of JSON that should be editable by hand.