In this article, we are going to parse the JSON file by displaying JSON data using PHP. PHP is a server-side scripting language used to process the data. JSON stands for JavaScript object notation. JSON data is written as name/value pairs.
Syntax:
{
“Data”:[{
“key”:”value”,
“key”:value,
“key n “:”value”
},
. . .
. . .
{
“key”:”value”,
“key”:value,
“key n “:”value”
}]
}
Example: The JSON notation for student details is as follows.
{
“Student”:[{
“Name”:”Sravan”,
“Roll”:7058,
“subject”:”java”
},
{
“Name”:”Jyothika”,
“Roll”:7059,
“subject”:”SAP”
}]
}
Advantages:
- JSON does not use an end tag.
- JSON is a shorter format.
- JSON is quicker to read and write.
- JSON can use arrays.
Approach: Create a JSON file and save it as my_data.json. We have taken student data in the file. The contents are as follows.
{
“Student”:[{
“Name”:”Sravan”,
“Roll”:7058,
“subject”:”java”
},
{
“Name”:”Jyothika”,
“Roll”:7059,
“subject”:”SAP”
}]
}
Use file_get_contents() function to read JSON file into PHP. This function is used to read the file into PHP code.
Syntax:
file_get_contents(path, file_name)
- file_name is the name of the file and path is the location to be checked.
- Use json_decode() function to decode to JSON file into array to display it.
It is used to convert the JSON into an array.
Syntax:
json_decode($json_object, true)
- $json_object is the file object to be read.
PHP code: The following is the PHP code to parse JSON file.
PHP
<?php
$json = file_get_contents ( 'my_data.json' );
$json_data = json_decode( $json ,true);
print_r( $json_data );
?>
|
Output:
Array (
[Student] => Array (
[0] => Array (
[Name] => Sravan
[Roll] => 7058
[subject] => java
)
[1] => Array (
[Name] => Jyothika
[Roll] => 7059
[subject] => SAP
)
)
)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!