JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. PHP provides functions to encode and decode JSON, making it easier to interact with APIs, save configuration data, or even communicate with JavaScript.
JSON represents data structures like objects and arrays:
Example:
{
"name": "John",
"age": 30,
"isStudent": false,
"subjects": ["Math", "English", "Science"],
"address": {
"street": "123 Main St",
"city": "Anytown"
}
}
Converts a PHP value into a JSON encoded string.
$arr = array(
'a' => 1,
'b' => 2,
'c' => 3
);
echo json_encode($arr);
Output:
{"a":1,"b":2,"c":3}
Converts a JSON encoded string into a PHP value.
$json = '{"a":1,"b":2,"c":3}';
$obj = json_decode($json);
print_r($obj);
Output:
stdClass Object
(
[a] => 1
[b] => 2
[c] => 3
)
If you want the result as an associative array instead of an object, set the second parameter of `json_decode()` to `true`.
$arr = json_decode($json, true);
print_r($arr);
Output:
Array
(
[a] => 1
[b] => 2
[c] => 3
)
The `json_last_error()` function returns the last error (if any) that occurred during JSON encoding/decoding.
Example:
$json = '{"a":1,"b":2,"c":3,}'; // Invalid JSON because of the trailing comma
$data = json_decode($json);
if (json_last_error() !== JSON_ERROR_NONE) {
echo 'JSON Error: ' . json_last_error_msg();
}
Output:
JSON Error: Syntax error
JSON is commonly used to send data from PHP to JavaScript on a webpage:
<script>
var data = ;
console.log(data);
</script>
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here