How to use JSON correctly in JavaScript and PHP

How to use JSON correctly in JavaScript and PHP Thumbnail
Published on 21. May 2019Last updated on 9. October 2020

JSON is an indispensable part for web applications. Learn how to properly exchange, store and convert JSON data between JavaScript (client-side) and PHP (server-side).

Advertisement

JSON stands for JavaScript Object Notation and is a very simple and compact data format to store and send data. Data is often exchanged between the user (client) and the server. In this article we will look at data transfer, storage and especially the conversion of arrays to JSON and vice versa.

1. What’s JSON?

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

This is an example of JSON. Here three entries with the attributes id and name are stored in the category ceos. This structure is very similar to the structure of multidimensional arrays. There is a reason for this, because the conversion between these two “data types” works quite well.

So that we can work properly, here is a JSON Validator, so that you can always check whether you have a valid JSON format. Otherwise it will not give the result you expect.

JSON Validator

Since we mainly focus on usage – especially in PHP and JavaScript – in this article, you can have a look at the exact structure of JSON in this article if you are interested.

Advertisement

2. JSON in PHP

2.1 Read out data

In principle, JSON data can be stored very easily. A simple text file is sufficient to store the data there. This is also a common and good solution for small amounts of data. But 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.

However, we assume small amounts of data and have a file on the server side, e.g. with the name storage.json with the following content (same content as the above example, only in minified)

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

With the following lines we can have the file read and output in PHP:

<?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 cannot 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:

Advertisement
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 output or change values of the object. So in this case it makes no difference to us whether we get an array or an 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
?>

2.2 Save data

Once we have adjusted our data as desired, we can save them 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 during readout, we have to encode it again before saving. This is done in PHP via json_encode(). That’s about it. Simple, right?

3. Send JSON from JavaScript to PHP (Ajax)

To request data on the client side I like to use jQuery, because I save some lines of JavaScript. We can do the same with other frameworks or libraries like Vue.js, you can find the corresponding functions in their documentation. 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.5.1/jquery.min.js"></script>
    <script>
        $.getJSON('server.php', {}, function(data) {
            console.log(data);
        });
    </script>
</body>
</html>

Of course you can also transfer the data by POST or GET.

<?php
// server.php

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

The JavaScript Console output looks like this:

Advertisement
JSON Console Log

So we have already in JavaScript normal access to the data, which originally comes from our storage.json.

4. JSON in JavaScript

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

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

let 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().

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

let obj = JSON.parse(json);

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

The 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"}]}

5. Conclusion

With this 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, using it in JavaScript and PHP is also very simple and intuitive. If you have any questions, please feel free to contact me via the comments! 🙂

Related Posts
NEW 🚀
Join the Conversation

2 Comments

  1. Thanks for this insightful tutorial — one thing I’ve noticed working with it, however, is that all numbers are treated as strings using this method. In some cases you may need to cast a string that stores only a number to a proper integer

    1. Thanks for your feedback! That’s right, for some operations it needs to be casted, thanks. 🙂

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