PHP JSON

Beginner
7 min read
Updated: Nov 2026
3 examples
Encode, decode & validate

Definition and Usage

JSON is a lightweight text format for structured data. It is the standard way for web APIs, JavaScript front ends, and config files to exchange information, and PHP can read and write it with a handful of built-in functions.

json_encode() converts a PHP array or object into a JSON string, and json_decode() converts a JSON string back into PHP data. When something goes wrong, json_last_error() and json_last_error_msg() explain why, and json_validate() (PHP 8.3+) checks a string without decoding it.

This page explains the ideas. The JSON Functions index lists all 5 function guides.

Decoding can fail quietly.

By default json_decode() returns null for bad input instead of raising an error. Pass the JSON_THROW_ON_ERROR flag so a JsonException is thrown, or check json_last_error() right after the call.

json_validate() needs PHP 8.3 or newer.

On older versions the function does not exist. Guard it with function_exists('json_validate') or fall back to json_decode() with JSON_THROW_ON_ERROR.

PHP Syntax

The usual round trip between PHP data and JSON text:

PHP
// 1. PHP data -> JSON string
$json = json_encode($value, $flags = 0, $depth = 512);

// 2. JSON string -> PHP data
$object = json_decode($json);                 // stdClass objects
$array  = json_decode($json, true);           // associative arrays

// 3. Throw instead of returning null / false on errors
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);

// 4. Inspect the last error (when not using JSON_THROW_ON_ERROR)
json_last_error();       // int code, JSON_ERROR_NONE (0) when fine
json_last_error_msg();   // readable message, "No error" when fine

// 5. Check validity only (PHP 8.3+)
json_validate($json);    // true or false

// json_encode(): the JSON string, or false on failure
// json_decode(): the decoded value, or null on failure

Core Ideas

What to remember when you work with JSON in PHP:

IdeaExampleRemember
Encodejson_encode($data)Returns a string, or false on failure; add JSON_PRETTY_PRINT for readable output
Decode to objectsjson_decode($json)JSON objects become stdClass; read values with ->
Decode to arraysjson_decode($json, true)JSON objects become associative arrays; read values with ['key']
List vs object[1, 2] vs ['a' => 1]A sequential PHP array encodes as a JSON array, a keyed array as a JSON object, and an empty array as []
Throw on errorsJSON_THROW_ON_ERRORRaises JsonException and leaves the global error state untouched
Error code and textjson_last_error(), json_last_error_msg()Report only the most recent encode or decode call
Validatejson_validate($json)PHP 8.3+; returns true or false without building the data
Unicode and slashesJSON_UNESCAPED_UNICODE, JSON_UNESCAPED_SLASHESKeep readable characters and URLs instead of \uXXXX and \/

PHP Examples

Three short scripts that show how JSON is used in PHP. The data is made up; replace it with your own.

Example 1 — Encode and decode

Turn a PHP array into a JSON string, then read it back and pick out one value.

PHP
<?php
$user = [
    'name'   => 'Asha',
    'age'    => 29,
    'skills' => ['PHP', 'SQL'],
    'active' => true,
];

$json = json_encode($user);
echo $json . "\n";

$data = json_decode($json, true);
echo $data['skills'][1] . "\n";
?>

How It Works

  1. json_encode() turns the keyed array into a JSON object. The inner list ['PHP', 'SQL'] becomes a JSON array, and true stays a JSON boolean.
  2. json_decode($json, true) reverses the process and returns an associative array because the second argument is true.
  3. $data['skills'][1] reads the second skill. Arrays start at index 0, so index 1 is SQL.

Example 2 — Associative arrays vs objects

Decode the same JSON both ways and see how an empty array and an empty object are encoded.

PHP
<?php
$json = '{"id":7,"profile":{"city":"Pune"}}';

// Default: objects, read with the arrow operator
$obj = json_decode($json);
echo $obj->profile->city . "\n";

// Second argument true: associative arrays
$arr = json_decode($json, true);
echo $arr['profile']['city'] . "\n";

var_dump(is_object($obj), is_array($arr));

// An empty PHP array is a JSON list; use stdClass for {}
echo json_encode([]) . ' ' . json_encode(new stdClass) . "\n";
?>

How It Works

  1. json_decode($json) builds nested stdClass objects, so the city is reached with $obj->profile->city.
  2. json_decode($json, true) builds nested arrays instead, so the same value is $arr['profile']['city'].
  3. var_dump() confirms the types: one result is an object and the other is an array.
  4. json_encode([]) cannot tell an empty list from an empty map, so it writes []. Encode new stdClass when you need {}.

Example 3 — Handle errors and use json_validate()

Decode invalid JSON, read the error code and message, catch a JsonException, and validate input on PHP 8.3+.

PHP
<?php
$bad = '{"name": "Asha",}';   // trailing comma is not valid JSON

// 1. Classic style: check the error state after the call
$data = json_decode($bad, true);
if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
    echo json_last_error() . ': ' . json_last_error_msg() . "\n";
}

// 2. Modern style: let PHP throw
try {
    json_decode($bad, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    echo 'Caught: ' . $e->getMessage() . "\n";
}

// 3. Validate only (PHP 8.3+)
if (function_exists('json_validate')) {
    var_dump(json_validate('{"ok":true}'));
    var_dump(json_validate($bad));
}
?>

How It Works

  1. json_last_error() returns 4 (JSON_ERROR_SYNTAX) and json_last_error_msg() returns the text Syntax error. The extra $data === null check avoids a false alarm when the JSON really is null.
  2. JSON_THROW_ON_ERROR turns the failure into a JsonException. The code 512 before it is the default nesting depth, which must be passed to reach the flags argument.
  3. json_validate() only answers true or false and builds no arrays or objects, which saves memory on large payloads. It exists in PHP 8.3 and newer, so the script checks function_exists() first.

Next: PHP JSON Functions Index

After you know the encode, decode, and error flow, open the function index for all 5 guides.

Start withWhy
json_encode()Convert PHP data to a JSON string
json_decode()Convert a JSON string to PHP data
json_last_error()Get the error code of the last JSON call
json_last_error_msg()Get the error message of the last JSON call
json_validate()Check whether a string is valid JSON (PHP 8.3+)

Full list: PHP JSON Functions index (/php/json/function).

Frequently Asked Questions

JSON (JavaScript Object Notation) is a text format for structured data that almost every language and web API understands. PHP has built-in functions to convert its arrays and objects to a JSON string with json_encode() and to turn a JSON string back into PHP data with json_decode().
By default json_decode() returns objects (stdClass) for JSON objects. Pass true as the second argument, json_decode($json, true), to get associative arrays instead. Arrays are convenient with array functions and ?? defaults; objects read nicely with the -> operator. Pick one style and use it consistently.
It returns null when the JSON is invalid, when the nesting is deeper than the depth limit, or when the JSON text is literally null. Because null can also be a valid result, check json_last_error(), or better, pass the JSON_THROW_ON_ERROR flag so a JsonException is thrown on failure.
json_last_error() returns an integer error code such as JSON_ERROR_SYNTAX, and JSON_ERROR_NONE (0) when the last call worked. json_last_error_msg() returns the matching human-readable text, such as Syntax error. Both describe only the most recent json_encode() or json_decode() call.
json_validate() was added in PHP 8.3. It checks whether a string is valid JSON and returns true or false without building any arrays or objects, so it uses less memory than json_decode() for large payloads. On PHP 8.2 and earlier it does not exist; use json_decode() with JSON_THROW_ON_ERROR instead.
Practice the examples here, then open the JSON Functions index for all 5 function guides: json_decode(), json_encode(), json_last_error(), json_last_error_msg(), and json_validate().

Browse every JSON function

Open the functions index for categorized guides with examples and FAQs.

JSON Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful