Using JSON correctly in JavaScript and PHP

Using JSON correctly in JavaScript and PHP

JSON is an indispensable part for web applications. Here you will learn how to exchange and store JSON data correctly between JavaScript (client-side) and PHP (server-side).

JSON stands for JavaScript Object Notation and is a very simple and compact data format for storing and sending data. Data is often exchanged between the user (client) and the server. In this article we look at the data transfer and storage of JSON.

{
  "ceos": [
    {
      "id": "1",
      "name": "Steve Jobs"
    },
    {
      "id": "2",
      "name": "Bill Gates"
    },
    {
      "id": "3",
      "name": "Paul Allen"
    }
  ]
}

This is an example for JSON. Three entries with the attributes id and name are stored in the category ceos.

You can validate and format your JSON with this tool.

Since I would like to go more into the use of JavaScript and PHP here, you can have a look at the exact structure of JSON in this article if you are interested.

Reading and saving JSON in PHP

Reading JSON

In principle, JSON data can be stored very easily. A simple text file is sufficient to store the data there. When it comes to small amounts of data, this is also a common and good solution. However, if you have a lot of data, or data that is added dynamically (like a contact form), it is recommended to store the data in a database.

But here we start from small amounts of data and on the server side we have a file named storage.json with the following content (same content as the example above, minified only):

{"heroes":[{"id":"1","name":"Steve Jobs"},{"id":"2","name":"Bill Gates"},{"id":"3","name":"Paul Allen"},{"id":"4","name":"Sundar Pichai"}]}

The following lines can be used to read in and output the file:

<?php 
$file = file_get_contents("storage.json");
print_r($file);
?>

The unformatted output gives us the simple text content of the file:

{"heroes":[{"id":"1","name":"Steve Jobs"},{"id":"2","name":"Bill Gates"},{"id":"3","name":"Paul Allen"},{"id":"4","name":"Sundar Pichai"}]}

We can’t do much with this data in this form. We could write our own parser to convert it into an object or array. But it is much easier.

PHP offers us the function json_decode() to convert the JSON string into an object.

<?php 
$file = file_get_contents("storage.json");
$json_decoded = json_decode($file);
print_r($json_decoded);
?>

The JSON string has been converted to an object and we can treat it like any other object in PHP. This output looks like this:

stdClass Object
(
    [heroes] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 1
                    [name] => Steve Jobs
                )

            [1] => stdClass Object
                (
                    [id] => 2
                    [name] => Bill Gates
                )

            [2] => stdClass Object
                (
                    [id] => 3
                    [name] => Paul Allen
                )

            [3] => stdClass Object
                (
                    [id] => 4
                    [name] => Sundar Pichai
                )

        )

)

As already mentioned we can now use normal object operators to display or change the values of the object:

<?php 
$file = file_get_contents("storage.json");
$json_decoded = json_decode($file);

echo $json_decoded->heroes[0]->name;	// Output: Steve Jobs

$json_decoded->heroes[0]->name = "CEO Steve Jobs";

echo $json_decoded->heroes[0]->name;	// Output: CEO Steve Jobs
?>

Save JSON

Once we have adjusted our data as desired, we can save it again.

<?php 
$filename = "storage.json";
$file = file_get_contents($filename);
$json_decoded = json_decode($file);

$json_decoded->heroes[0]->name = "CEO Steve Jobs";

$json_encoded = json_encode($json_decoded);
file_put_contents($filename, $json_encoded);
?>

Since we decoded the JSON string while reading it out, we have to encode it again before saving it. This is done in PHP via json_encode(). That’s it, too. Simple, isn’t it?

Send JSON from PHP to JavaScript

To request data on the client side I like to use jQuery. Here is an example, which makes an Ajax request to our server.php and gets the data returned.

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>JSON in JavaScript and PHP</title>
</head>

<body>

    <script loading="lazy" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
        $.getJSON('server.php', {}, function(data) {
            console.log(data);
        });
    </script>
</body>

</html>

server.php

<?php
$file = file_get_contents("storage.json");
exit($file);
?>

The console output looks like this:

JSON Console Log

This gives us normal access in JavaScript to the data that originally came from our storage.json.

JSON in JavaScript

If we now have a JSON string in JavaScript, we can convert it to a JavaScript object using the JSON.parse() function. It looks like this:

var json = '{"heroes":[{"id":"1","name":"CEO Steve Jobs"},{"id":"2","name":"Bill Gates"},{"id":"3","name":"Paul Allen"},{"id":"4","name":"Sundar Pichai"}]}';

var obj = JSON.parse(json);
console.log(obj);

The output is identical to the output from our storage.json.

JSON Console Log

Conversely, we can convert a JavaScript object to JSON with JSON.stringify().

var json = '{"heroes":[{"id":"1","name":"CEO Steve Jobs"},{"id":"2","name":"Bill Gates"},{"id":"3","name":"Paul Allen"},{"id":"4","name":"Sundar Pichai"}]}';

var obj = JSON.parse(json);

var jsonAgain = JSON.stringify(obj);
console.log(jsonAgain);

The console output is then again our JSON string, which we also have in the variable json.

{"heroes":[{"id":"1","name":"CEO Steve Jobs"},{"id":"2","name":"Bill Gates"},{"id":"3","name":"Paul Allen"},{"id":"4","name":"Sundar Pichai"}]}

Conclusion

We have discussed the most important JSON functions for JavaScript and PHP. JSON is simply a very simple and compact data format. As you have now seen, the use in JavaScript and PHP is also quite simple. If you have any questions, please feel free to contact me via the comments! 🙂

NEW 🚀
NEW 🚀
NEW 🚀

Leave a comment

Your email address will not be published. Required fields are marked *