JSON (JavaScript Object Notation) is a lightweight data exchange format that is easy for humans to read and write, and easy for computers to parse and generate. It describes data using objects and is commonly used for transferring data between servers and webpages.
Example of JSON format:
<span class="fun">{"name": "John", "age": 18, "gender": "Male"}</span>
In JSON format, the data appears as key-value pairs where the key and value are separated by a colon, data items are separated by commas, and the entire data is enclosed within curly braces.
In PHP, the json_decode() function is used to convert JSON data into a PHP array.
Example code:
$json = '{"name": "John", "age": 18, "gender": "Male"}';
$arr = json_decode($json, true);
print_r($arr);
Output:
Array
(
[name] => John
[age] => 18
[gender] => Male
)
In PHP, the json_encode() function is used to convert a PHP array into JSON format.
Example code:
$arr = array("name" => "John", "age" => 18, "gender" => "Male");
$json = json_encode($arr);
echo $json;
Output:
<span class="fun">{"name":"John","age":18,"gender":"Male"}</span>
Using JSON data enables the front-end and back-end separation. The front-end can retrieve JSON data via AJAX from the back-end and perform necessary DOM operations without frequent interactions with the back-end.
The front-end uses AJAX to get JSON data from the back-end API and then processes it accordingly.
$.ajax({
url: "test.php", // Back-end API
type: "get",
dataType: "json", // Specifies that the response is JSON data
success: function(data) {
console.log(data); // Output the received JSON data
}
});
Once the front-end receives the JSON data, it can parse it using JavaScript and display the data on the page.
$.ajax({
url: "test.php", // Back-end API
type: "get",
dataType: "json", // Return JSON data
success: function(data) {
// Parse the JSON data
var name = data.name;
var age = data.age;
var gender = data.gender;
// Display the data on the page
$("#name").text(name);
$("#age").text(age);
$("#gender").text(gender);
}
});
This article introduced the basic concept of JSON and the methods for parsing JSON data in PHP, including converting JSON to PHP arrays and converting PHP arrays to JSON format. It also explained how to use AJAX to retrieve JSON data and process it on the front-end, enabling front-end and back-end separation, improving user experience and website performance.