How creating JSON in PHP manually is better for beginners

Whether you need JSON to feed to your data visualizations like charts and maps or you simply need to send a HTTP request with correctly formatted JSON. This tutorial with give you the knowledge on how to create properly formatted JSON ready to be injected into your JavaScript tags. This guide will demo a few different ways to get to the main goal of converting PHP data into java script object notation (JSON).

Why creating JSON manually helps you understand JSON better

The following method of creating JSON within a loop would probably be seen as a ‘quick and dirty way of coding’. But having said this, I believe doing it this way when beginning with JSON, can be a great learning tool. Rather than using one of PHP’s built in encoding functions like json_encode, you can type the code manually to output the required result.

When coding the JSON manually, you get to see finer detail of how JSON goes together. Learning you things like –

  • Where commas must be placed.
  • Where square brackets have to be placed.
  • Where curly braces begin and end and how they section out data nodes.
  • Where quotations must and must not be placed.
  • Where identifiers and values sit within the JSON.

In addition to the above, some JavaScript libraries require JSON in some super-funky ways, meaning that in some cases, encoding may not be suitable. Therefore, manually is the only option, so again, this method can be invaluable. By coding JSON manually you will ultimately get a deeper understanding of how the formatting of JSON works.

Repeating the methods demonstrated within this article will drum the formatting into your head. Eventually, it will be second nature to throw together multiple level JSON without breaking a sweat.

Method – Creating JSON within a PHP while loop

In the following PHP code, I will demonstrate converting a database query result within a while loop. The output that is desired is a simple list of usernames. Meaning that the JSON will have a label of ‘username’ and a value of the actual username row.

Code
            $result = $statement->get_result(); // usernames result from DB.

            $json = "["; //Create variable with prepended bracket ready to append to.
            $i=0; // Index to manage where our commas go.
            while ($row = $result->fetch_assoc()) {
                if ($i == 0) // Run this if block once.
                {
                    $json .= '{"username" : "'.$row["username"].'" }';
                }
                else
                {
                    $json .= ', {"username" : "'.$row["username"].'" }'; // prepend the json with a comma for each loop.
                }
                $i++; // Increase by one so that the else statement is ran until the end of the data.
            }
            $json .= "]"; // Finally, close the json with the last square bracket.
            
            echo $json;
Output of the json variable
[{
	"username": "rogers63"
}, {
	"username": "mike28"
}, {
	"username": "rivera92"
}, {
	"username": "ross95"
}, {
	"username": "paul85"
}, {
	"username": "smith34"
}, {
	"username": "james84"
}]

As you can see the output is perfect JSON, and when dropped in a JSON Lint tool, it validates correctly. Some important things to note here about the PHP code are as follows –

  • We create the $json variable before we enter the while loop so it can be pre-populated with the required beginning square bracket.
  • We create a number variable, $i, so we can control where commas are placed throughout looping.
  • With the $i variable, we use within a IF statement so the first block runs once and the second runs until the data ends.
  • We increase the $i after the first loop, so what is stated in the last bullet point happens.
  • Within the Else block, we prepend the $json variable with a comma, so we never have a trailing comma at the end of the looping.
  • Finally, once the loop is broken out of, we add the remaining square bracket to close the JSON.

Summary

At the beginning of this article, I mentioned that creating JSON in the method shown would be frowned upon. I can guarantee that statement is true. But the vital fact here is that doing it this way helps with learning. Yes it looks messy and much more code than a single-liner but it totally depends if you’re intrigued on knowing JSON formatting well, or not.

Interesting Links

Leave a comment if you don’t agree, I would love to talk about it!

How creating JSON in PHP manually is better for beginners
Posted in PHP

You May Also Like

Leave a Reply

Your email address will not be published.