Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 147 Β· Working with Files

JSON

Work with JSON in PHP - json_encode and json_decode, arrays vs objects, JSON_PRETTY_PRINT and JSON_THROW_ON_ERROR, json_validate in PHP 8.3 and JsonSerializable.

JSON (JavaScript Object Notation) is the data format of the modern web. APIs send and receive it, JavaScript in the browser speaks it natively, configuration files and caches store it, and databases like MySQL and PostgreSQL have JSON columns. If your PHP code talks to anything else, it almost certainly talks JSON.

PHP's support comes down to two functions: json_encode() turns PHP values into a JSON string, and json_decode() turns a JSON string back into PHP values. They're simple to call, but the defaults hide a few traps: decoding gives you objects unless you ask for arrays, errors are silent unless you ask for exceptions, and an array can come out as a JSON list or a JSON object depending on its keys. This lesson covers both functions, the flags that matter, error handling, json_validate() from PHP 8.3, and how to control the JSON for your own classes with JsonSerializable.

JSON in one minute

JSON has six kinds of values, and each maps to a PHP type:

JSON Example PHP after decoding
object {"name": "Ada", "age": 36} stdClass object, or associative array
array [1, 2, 3] indexed array
string "hello" (double quotes only) string
number 42, 3.14, -1e3 int or float
boolean true, false bool
null null null

JSON is stricter than PHP or JavaScript syntax: keys must be double-quoted strings, there are no comments, no trailing commas, and no single quotes. Text must be UTF-8.

Encoding: json_encode

json_encode($value) returns the JSON text for almost any PHP value: scalars, arrays, objects (their public properties), and nested combinations of them.

PHP Encoding PHP values as JSON

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first line is compact JSON, ideal for sending over the network:

TEXT
{"id":17,"name":"CafΓ© table","price":149,"tags":["wood","outdoor"],"discount":null,"inStock":true,"url":"https:\/\/example.com\/p\/17"}

Three things look odd at first. The Γ© became Γ©, the slashes in the URL became \/, and 149.0 lost its decimal part. All of it is valid JSON and decodes correctly, but it's harder for humans to read. The flags in the second call fix each one:

Flag Effect
JSON_PRETTY_PRINT Line breaks and 4-space indentation
JSON_UNESCAPED_UNICODE Write Γ©, €, ζ—₯本 as real UTF-8 instead of \uXXXX
JSON_UNESCAPED_SLASHES Write / instead of \/
JSON_PRESERVE_ZERO_FRACTION Write 149.0 instead of 149 for floats
JSON_THROW_ON_ERROR Throw JsonException on failure (see below)
JSON_FORCE_OBJECT Encode every array as an object
JSON_NUMERIC_CHECK Turn numeric strings into numbers (risky: it also converts phone numbers and zip codes)
JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_HEX_QUOT Escape <, >, &, ', " as < etc., for embedding JSON inside HTML

Combine flags with |. A sensible default for APIs is JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES.

Why does PHP escape / by default? So that JSON placed inside an HTML <script> tag can never contain </script>, which would end the script early. If you embed JSON in HTML, keep the slash escaping and add the JSON_HEX_* flags; for API responses you can drop it.

Lists vs objects: how arrays are encoded

PHP has one array type; JSON has two (arrays and objects). json_encode() decides per array: if the keys are exactly 0, 1, 2, ... in order (what array_is_list() checks), it writes a JSON array; otherwise it writes a JSON object. That rule has a famous trap:

PHP When an array becomes an object

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

array_filter() keeps the original keys, so after removing 7 the keys are 0, 1, 3, no longer a list, and the result is the object {"0":10,"1":25,"3":31}. A JavaScript client expecting an array breaks. array_values() renumbers the keys and gives [10,25,31] again. Whenever you filter or unset elements before encoding, reindex.

The second trap is the empty array: [] always encodes as []. If your API promises an object (say, an empty settings map), encode an empty stdClass or cast with (object) [], which gives {}.

Objects

For an object, json_encode() includes only its public properties. Private and protected ones are skipped, which is usually what you want but sometimes surprising. To choose exactly what goes into the JSON, implement JsonSerializable, covered at the end of this lesson. Backed enums encode as their value ("paid"), and pure enums can't be encoded at all.

Decoding: json_decode

json_decode($json) parses JSON text. By default, JSON objects become stdClass objects, which you access with ->. Pass true as the second argument (or associative: true) to get associative arrays instead:

PHP Decoding to objects or arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Both forms hold the same data. Arrays are usually more convenient in PHP: every array function works on them (array_column() sums the quantities here), they're easy to var_dump(), and a missing key can be handled with ??. Objects are slightly more natural when you'll hand the data to code that expects -> access. Most PHP code, including Laravel's request helpers, decodes to arrays.

The last line shows that json_decode() also accepts plain scalars: 3.0 becomes float(3), "text" becomes a string, and null becomes NULL.

Other parameters: depth (default 512) limits how deeply nested the data may be, and the flag JSON_BIGINT_AS_STRING keeps integers too big for PHP's 64-bit int as strings instead of turning them into imprecise floats.

Handling errors

Here's the trap with the defaults: when decoding fails, json_decode() returns null without a warning. But null is also the correct result for the valid JSON text null. So you can't tell "broken input" from "the input was null" by the return value alone. Before PHP 7.3 the only way was to call json_last_error() afterwards. Today, use JSON_THROW_ON_ERROR, which makes both functions throw a JsonException with a clear message:

PHP JSON_THROW_ON_ERROR and JsonException

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The trailing comma and the single quotes both give NULL by default, exactly like the valid input null. With the flag, the broken inputs throw JsonException: Syntax error, while null decodes fine. json_last_error_msg() describes the last error (No error after success).

Encoding can fail too. The most common cause is a string that isn't valid UTF-8, often text read from an old file or database in a legacy encoding. By default json_encode() returns false then, which quietly turns into an empty response body. With the flag you get Malformed UTF-8 characters, possibly incorrectly encoded. If you'd rather replace bad bytes than fail, add JSON_INVALID_UTF8_SUBSTITUTE, which writes the replacement character οΏ½ instead.

Make JSON_THROW_ON_ERROR a habit for every json_encode() and json_decode() call. It costs nothing, and it turns silent data loss into an exception with a precise message. Note that json_decode()'s flags are its fourth parameter, so use a named argument (flags: JSON_THROW_ON_ERROR) or pass the defaults: json_decode($json, true, 512, JSON_THROW_ON_ERROR).

json_validate (PHP 8.3)

Sometimes you only need to know whether a string is valid JSON, for example to validate an API field before storing it. Decoding just to check wastes memory, because it builds the whole PHP structure. PHP 8.3 added json_validate(), which checks the syntax without building anything:

PHP Checking JSON with json_validate

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The unclosed array and the empty string are invalid (Syntax error); a lone string is valid JSON. json_validate() accepts the same depth and only the JSON_INVALID_UTF8_IGNORE flag. If you're going to use the data anyway, skip the validation step and decode once with JSON_THROW_ON_ERROR; validating and then decoding parses the text twice.

Reading and writing JSON files

JSON files are a common way to store settings, fixtures and small caches. Combine the JSON functions with file_get_contents() and file_put_contents():

PHP A small JSON settings file

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

array_replace() lays the stored values over the defaults, so a settings file written by an older version of the app (missing a newer key) still works. The saved file is pretty-printed with the Β‘ kept readable thanks to JSON_UNESCAPED_UNICODE, and it ends with a newline, which plays well with version control and command-line tools.

For JSON APIs, the reading side is file_get_contents('php://input') for the request body and the writing side is header('Content-Type: application/json') plus echo json_encode(...). Building a JSON API covers that properly.

Controlling the output: JsonSerializable

When you encode your own objects, you usually don't want "all public properties". You might need to hide a password hash, rename fields, format a date or a money amount, or include a computed value. Implement the JsonSerializable interface: its single method, jsonSerialize(), returns whatever should be encoded in place of the object:

PHP Custom JSON with JsonSerializable

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The JSON contains exactly the five fields from jsonSerialize(): the total as the string "49.90" (strings avoid float rounding in clients when money is involved), the enum as its value "paid", and the date in ISO 8601 format (2026-10-18T09:30:00+00:00). The private note never leaks. Without the interface, json_encode() would output the public properties, and the DateTimeImmutable would appear as an object with date, timezone_type and timezone fields that clients would have to understand.

Decoding never gives you an Order back, only arrays (or stdClass). Rebuilding objects is up to you: here OrderStatus::from() turns the string back into the enum. Frameworks and libraries like Symfony Serializer automate that mapping in both directions.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What does json_encode(array_filter([5, 0, 8])) produce?

    array_filter removes 0 but keeps the keys 0 and 2. Those keys aren't a list, so the array is encoded as an object. Use array_values() to get [5,8].
  2. 2. What does json_decode('{"a": 1}') return?

    Without the associative argument, JSON objects become stdClass objects. Pass true as the second argument to get an array.
  3. 3. json_decode('{bad json}', true) without flags returns null. Why is that a problem?

    The default behavior is silent. JSON_THROW_ON_ERROR throws a JsonException with a message such as Syntax error.
  4. 4. Which flags make json_encode write Γ© and / as-is instead of Γ© and /?

    These two flags keep UTF-8 characters and slashes readable. The output is equally valid either way.
  5. 5. A class implements JsonSerializable. What does json_encode() output for an instance?

    jsonSerialize() replaces the default behavior (public properties only), so you choose the fields, names and formats.

Summary

  • json_encode() turns PHP values into JSON; json_decode() parses JSON. JSON has objects, arrays, strings, numbers, booleans and null, with strict syntax (double quotes, no comments, no trailing commas, UTF-8).
  • Useful encode flags: JSON_PRETTY_PRINT, JSON_UNESCAPED_UNICODE, JSON_UNESCAPED_SLASHES, JSON_PRESERVE_ZERO_FRACTION, JSON_FORCE_OBJECT; the JSON_HEX_* flags when embedding in HTML.
  • Arrays with keys 0, 1, 2, ... become JSON arrays, anything else becomes an object: reindex with array_values() after filtering. [] encodes as []; use (object) [] for {}.
  • json_decode($json) gives stdClass objects; json_decode($json, true) gives associative arrays, which most PHP code prefers.
  • Always use JSON_THROW_ON_ERROR: without it, failures return null or false silently. Catch JsonException. Invalid UTF-8 is the usual encoding failure.
  • json_validate() (PHP 8.3) checks syntax without building data; don't validate and then decode the same text.
  • Implement JsonSerializable to control how your objects are encoded: hide private data, format dates and money, use enum values. Decoding never rebuilds your objects automatically.

Next: XML