DEV Community

Cover image for JSON in JavaScript and PHP: Read, Get, Send, Convert [BASICS]
webdeasy.de
webdeasy.de

Posted on • Originally published at webdeasy.de

JSON in JavaScript and PHP: Read, Get, Send, Convert [BASICS]

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.


❓ 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"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

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.

👨‍💻 JSON IN PHP

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"}]}
Enter fullscreen mode Exit fullscreen mode

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

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

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"}]}
Enter fullscreen mode Exit fullscreen mode

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);
?>
Enter fullscreen mode Exit fullscreen mode

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
                )
        )
)
Enter fullscreen mode Exit fullscreen mode

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
?>
Enter fullscreen mode Exit fullscreen mode

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);
?>
Enter fullscreen mode Exit fullscreen mode

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?

📨 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>
Enter fullscreen mode Exit fullscreen mode
<?php
// server.php
$file = file_get_contents("storage.json");
exit($file);
?>
Enter fullscreen mode Exit fullscreen mode

The JavaScript Console output looks like this:
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.

👨‍💻 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);
Enter fullscreen mode Exit fullscreen mode

The output is identical to the output from our storage.json.
JSON Console Log<br>

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

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"}]}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (1)

Collapse
 
efpage profile image
Eckehard

Both working with and debugging PHP is a bit awkward to me and I tend to minimize the PHP code on my pages. But often enough it is the only usable option, as node.js is not available on all webservers. And it is fairly convenient if you want to use SQlite as a database, which makes backup really easy. So, there are some reasons to use PHP even if you do not like the whole approach.

Anyway, modifying the PHP source can be a nightmare for me, so I was wandering, if there is any solution that let´s me work with PHP without modifying the code. Maybe there is some kind of generic database adapter that can be used from Javascript.

OK, AJAX is not too complicated, but I assume there are people that do a better job than me to build a PHP infrastructure.