Native JSON Support in PHP
PHP has built-in JSON functions since PHP 5.2, with important improvements in PHP 7.3+ (JSON_THROW_ON_ERROR) and PHP 8.
Core Functions:
json_decode($json, true)— Parse JSON to associative array (true) or stdClass object (false/null).json_encode($value, JSON_PRETTY_PRINT)— Serialize PHP value to JSON string.json_last_error()— Returns last JSON error code (legacy error checking).
json
<?php
// Parse JSON to associative array
$json = '{"name":"Alice","score":99,"active":true}';
$data = json_decode($json, true); // true = assoc array
echo $data['name']; // Alice
// Serialize PHP array to JSON
$arr = ['name' => 'Bob', 'score' => 85];
echo json_encode($arr);
// {"name":"Bob","score":85}
// Pretty print JSON
echo json_encode($arr, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
// PHP 7.3+ — Throw exception on error
try {
$data = json_decode($invalidJson, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo "JSON error: " . $e->getMessage();
}