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

Table of contents

  • Reading and saving JSON in PHP
  • Read JSON
  • Save JSON
  • Send JSON from PHP to JavaScript
  • JSON in JavaScript
  • Conclusion

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] =&gt; stdClass Object
            (
                [id] =&gt; 2
                [name] =&gt; Bill Gates
            )

        [2] =&gt; stdClass Object
            (
                [id] =&gt; 3
                [name] =&gt; Paul Allen
            )

        [3] =&gt; stdClass Object
            (
                [id] =&gt; 4
                [name] =&gt; 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>

&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"&gt;&lt;/script&gt;
&lt;script&gt;
    $.getJSON('server.php', {}, function(data) {
        console.log(data);
    });
&lt;/script&gt;

</body>

</html>

server.php

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

The console output looks like this:


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.


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! 

Originally published  at webdeasy.de on 21. May 2019

========================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

☞ The complete beginner’s guide to JSON

☞ The Complete Guide to JSON Web Tokens

☞ Svelte.js - The Complete Guide

☞ The Complete JavaScript Course 2019: Build Real Projects!

☞ The Complete Node.js Developer Course (3rd Edition)

☞ PHP for Beginners - Become a PHP Master - CMS Project

☞ Learn Object Oriented PHP By Building a Complete Website

☞ MEVP Stack Vue JS 2 Course: MySQL + Express.js + Vue.js +PHP

☞ Object Oriented PHP & MVC

☞ PHP OOP: Object Oriented Programming for beginners + Project

json javascript php

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

PHP json_decode Example | Decode JSON Data in PHP Tutorial

PHP json_decode is an inbuilt function that takes the JSON encoded string and converts it into a PHP variable. JSON stands for JavaScript Object Notation.

Convert PHP Object To JSON | PHP Array To JSON

Convert PHP Array to JSON. In this tutorial we’ll learn about the JSON format and how to convert PHP data structures into JSON. Convert PHP Object to JSON.

JSON Tutorial For Beginners | What is JSON | Learning JSON with JavaScript

JSON Tutorial For Beginners | What is JSON | Learning JSON with JavaScript

Hire PHP Developer

Looking to develop a PHP based website from scratch or revamp your existing website? **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")** has always been an industry leader for companies and business owners looking to hire...

Javascript | How To Covert Javascript Array To JSON

In this example, we will see How To Covert Javascript Array To JSON. We can convert Javascript array to json using JSON.stringify() method. At some point in your time, whatever developer you are, you need to deal with JSON data. JSON stands for Javascript Object Notation. Exchange data between client and server is straightforward using JSON.