How to parse JSON

Pre-requisites: Basic Understanding HTML and JQuery.


In this project:

  • We will use json_encode()  and json_decode() functions to parse JSON data.

parseJSON.php file:

<?php
    // JSON ENCODE
    $indexedArr = array("Asia", "Africa", "Australia", "Europe", "Antartica");
    echo "Index Array JSON <br>";
    echo json_encode($indexedArr);

    echo "<br></br>";

    echo "Associative Array JSON <br>";
    $associativeArr = array("Smith" => 92, "Chris" => 80, "John" => 95, "Steve" => 96);
    echo json_encode($associativeArr);
    echo "<br><br>";

    // JSON DECODE
    $json = '{"Smith":92,"Chris":80,"John":95,"Steve":96}';
    $outputArr = json_decode($json);
    echo "<table border='1' cellpadding='6' cellspacing='0'>
            <tr>
                <th>Name</th>
                <th>Marks</th>
            </tr>";
    foreach($outputArr as $name => $marks){
        echo "<tr>";
        echo "<td>".$name."</td>";
        echo "<td>".$marks."</td>";
        echo "</tr>";
    }
    echo "</table>";
?>

Run parseJSON.php file in your browser to get the following output. URL may look like as follows:

Code Explanation of parseJSON.php

1.

$indexedArr = array(
   "Asia", "Africa", "Australia", "Europe", "Antartica"
);

Declaring and initializing an indexed array.

2.

json_encode($indexedArr);

json_encode is used to encode a PHP array to JSON string.

3.

json_decode($json);

json_decode() is used to decode a JSON string into an array.


Summary

In this project, we have learned to parse a PHP array into a JSON string using json_encode function.

We have also learned to parse JSON string to a PHP array using json_decode function. This is how, we exchange data in a standard format.

It is a language independent data format, therefore it can be easily used with other programming languages as well.

Help Us to Improve our content

Let's Talk