JSON in JavaScript and PHP: Read, Get, Send, Convert [BASICS]
Tags: php, webdev, javascript, beginners
Published: 2023-11-15 16:00:00

_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](https://webdeasy.de/en/rest-api-testing/).

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.
```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 right away, here is a link to a [JSON validator](https://jsonformatter.org/) so that you can always check whether you have a valid JSON format. I would also recommend installing a JSON [VSCode extension](https://webdeasy.de/en/top-vscode-extensions-en/) 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](https://www.json.org/json-de.html) 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](https://webdeasy.de/en/php-database-class/).

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)
```json
{"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
<?php 
$file = file_get_contents("storage.json");
print_r($file);
?>
```
The unformatted output gives us the simple text content of the file:
```json
{"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()`](https://www.php.net/manual/de/function.json-decode.php) to convert the JSON string into an object.
```php
<?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
<?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 our JSON data in PHP.
```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()`](https://www.php.net/manual/de/function.json-encode.php). 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](https://webdeasy.de/en/jquery-to-javascript/), because I save some lines of JavaScript. We can do the same with other frameworks or libraries like [Vue.js](https://webdeasy.de/en/3-practical-examples-vue-js/), you can find the corresponding functions in their documentation. Here is an example, which makes an [ajax](https://api.jquery.com/jquery.ajax/) request to our server.php and gets the data returned.

```html
<!-- 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
<?php
// server.php
$file = file_get_contents("storage.json");
exit($file);
?>
```
The JavaScript Console output looks like this:
![JSON Console Log](https://webdeasy.de/wp-content/uploads/2019/05/json-console-log.png)

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](https://webdeasy.de/en/ajax-in-wordpress-en/).


## 👨‍💻 JSON IN JAVASCRIPT
But if we have a JSON string in JavaScript, we can convert it to a JavaScript object using the [`JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse?retiredLocale=de) function. That looks like this:
```javascript
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
](https://webdeasy.de/wp-content/uploads/2019/05/json-console-log-1.png)

Conversely, we can convert a JavaScript object to JSON with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify?retiredLocale=de).

The output is then again our JSON string, which we also have in the variable `json`.
```json
{"heroes":[{"id":"1","name":"CEO Steve Jobs"},{"id":"2","name":"Bill Gates"},{"id":"3","name":"Paul Allen"},{"id":"4","name":"Sundar Pichai"}]}
```

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