JSON in PHP and JavaScript: Read, Get, Send, Convert, etc.

In this tutorial you will learn all the JSON basics – JSON in PHP, JSON in JavaScript and how to exchange/send JSON between JavaScript and PHP.

1. What’s JSON?

JSON stands for JavaScript Object Notation and is an uncomplicated and space-saving data format that is used to store and transmit information.

Data can be exchanged between the user (client) and the server. JSON is typically used as the format for Rest APIs.

I will show you how to create and process JSON on the client side with JavaScript and then transfer it to the server with Ajax. There it is processed further with PHP. We look at data transfer, storage and especially the conversion of arrays to JSON and vice versa.

{
  "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 right away, here is a link to a JSON validator so that you can always check whether you have a valid JSON format. I would also recommend installing a JSON VSCode extension to display code highlighting and linting directly in the IDE.

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.

2. JSON in PHP

2.1 Read JSON

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:

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 JSON

Once we have adjusted our data as desired, we can save our JSON data in PHP.

<?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 PHP and JavaScript</title>
</head>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
        $.getJSON('server.php', {}, function(data) {
            console.log(data);
        });
    </script>
</body>
</html>
<?php
// server.php

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

The JavaScript Console output looks like this:

JSON Console Log
JSON Console Log

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

By the way: WordPress has its own functions to manage Ajax data – learn how here.

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
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

Both PHP and JavaScript provide functions that simplify working with JSON, a straightforward and efficient data format for exchanging data between the two languages. This is typically the optimal choice for most web development and design use cases.

Related Posts
Join the Conversation

5 Comments

  1. Number Number Number String says:

    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. Lorenz says:

      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 *

bold italic underline strikeThrough
insertOrderedList insertUnorderedList outdent indent
removeFormat
createLink unlink
code

This can also interest you