JavaScript Object Notation (JSON) is a simple way to define an object along with its properties and their values. The notation has the name it does because it works directly in JavaScript as a way to define objects. Its use isn't just limited to JavaScript though as the notation provides a relatively short way of passing a lot of information in a small number of characters. By serializing JSON into a string we can easily pass a significant amount of information from one script to another in a single string that we just need to parse back into an object at its destination.

In JavaScript the conversion to and from a string are handled by JSON.stringify() and JSON.parse(). PHP provides functions to perform equivalent tasks with json_encode() and json_decode() which convert a PHP object to a JSON string and back. A string created using json_encode() in PHP can also be read by JavaScript and converted into the corresponding JavaScript object and vice versa.

JSON is much shorter than the equivalent PHP. Consider the following $arr object that we have created in PHP that has five properties each with a different value. The json_encode() call will result in the JSON equivalent being output to the page:

$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);

Running this code results in the following being written to the page.


We can then either pass this result to JavaScript if the current PHP is being called from a JavaScript ajax request where it can then be parsed and processed in JavaScript or we can convert it back into a PHP object. Let's assume that instead of echoing the JSON that we have assigned it to a variable. We'll than dump the result of doing a json_decode():

$json = json_encode($arr);
var_dump(json_decode($json, true));

This results in the following being written to the page (the true in the second parameter converts the object being returned into an associative array which is what we started with and so gives the same end result as calling var_dump on the original associative array):

array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow