Need help with your JSON?

Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool

PHP JSON Formatting Functions and Libraries

What Most PHP Projects Should Use

If you need to pretty-print JSON, build API responses, or parse JSON from a request or third-party API, start with PHP's built-in JSON extension. For most applications, json_encode() and json_decode() are enough, and modern code should usually add JSON_THROW_ON_ERROR so failures become exceptions instead of silent false or null values.

  • Use json_encode() to serialize and format PHP data.
  • Use json_decode() to parse JSON into arrays or objects.
  • Use json_validate() only when you need to check JSON syntax without decoding it. This was added in PHP 8.3.
  • Reach for a library when you need object mapping, schema-driven normalization, or streaming very large JSON files.

The Core Functions: json_encode() and json_decode()

These are the two functions you will use most often:

  • json_encode(mixed $value, int $flags = 0, int $depth = 512): string|false: Converts a PHP value into a JSON string.
  • json_decode(string $json, ?bool $associative = null, int $depth = 512, int $flags = 0): mixed: Parses JSON into PHP values. Set $associative to true if you want arrays instead of stdClass objects.

PHP arrays with sequential zero-based numeric keys become JSON arrays. Associative arrays and objects become JSON objects. That sounds simple, but it matters when your data has missing numeric indexes or when you are returning data to JavaScript clients that expect a consistent shape.

Formatting JSON with json_encode()

Pretty printing is just one part of JSON formatting. In practice, the useful flags are the ones that keep output readable without unexpectedly changing the data.

Example: Pretty, readable JSON output

<?php
$payload = [
    'name' => 'Sofiia',
    'profileUrl' => 'https://offlinetools.org/tools/json-formatter',
    'price' => 12.0,
    'tags' => ['php', 'json', 'formatting'],
    'message' => 'Hello, мир'
];

$json = json_encode(
    $payload,
    JSON_PRETTY_PRINT
    | JSON_UNESCAPED_SLASHES
    | JSON_UNESCAPED_UNICODE
    | JSON_PRESERVE_ZERO_FRACTION
    | JSON_THROW_ON_ERROR
);

echo $json;
?>

Output:

{
    "name": "Sofiia",
    "profileUrl": "https://offlinetools.org/tools/json-formatter",
    "price": 12.0,
    "tags": [
        "php",
        "json",
        "formatting"
    ],
    "message": "Hello, мир"
}

Flags That Matter in Real Projects

  • JSON_PRETTY_PRINT: Adds indentation and line breaks for logs, debugging, or developer-facing exports.
  • JSON_UNESCAPED_SLASHES: Keeps URLs readable instead of escaping every slash.
  • JSON_UNESCAPED_UNICODE: Outputs UTF-8 characters directly instead of \uXXXXescapes.
  • JSON_PRESERVE_ZERO_FRACTION: Keeps 12.0 as 12.0 instead of turning it into 12.
  • JSON_THROW_ON_ERROR: Preferred in new code because it throws JsonException on failure.
  • JSON_INVALID_UTF8_SUBSTITUTE: Replaces bad UTF-8 sequences instead of failing the entire encode.

Avoid JSON_NUMERIC_CHECK unless you are certain every numeric-looking string should become a number. It can quietly alter phone numbers, ZIP codes, IDs, and other values that should stay strings.

Safer Decoding with json_decode()

Older PHP examples often rely on json_last_error(). That still works, but for current code the safer default is to use JSON_THROW_ON_ERROR and catch JsonException.

Example: Decode JSON with exceptions

<?php
$requestBody = '{"userId": 9007199254740993123, "active": true}';

try {
    $data = json_decode(
        $requestBody,
        true,
        512,
        JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING
    );

    var_dump($data);
} catch (JsonException $e) {
    http_response_code(400);
    echo 'Invalid JSON: ' . $e->getMessage();
}
?>
  • Pass true as the second argument if you want associative arrays. This is the most common choice in plain PHP apps and API handlers.
  • Use JSON_BIGINT_AS_STRING when incoming JSON may contain integers larger than PHP can safely represent as numeric values.
  • Keep the default depth unless you have a specific reason to change it. Extremely deep payloads are often a data-quality problem, not just a parser setting.

When to Use json_validate()

PHP 8.3 added json_validate(), which checks whether a string is syntactically valid JSON without building the decoded PHP value in memory. That makes it useful when you only need a yes or no answer, such as request prechecks or guard clauses.

Example: Validate without decoding

<?php
$input = file_get_contents('php://input');

if (!json_validate($input)) {
    http_response_code(400);
    echo 'Request body must be valid JSON.';
    exit;
}

echo 'JSON syntax is valid.';
?>

Do not call json_validate() immediately before json_decode() on the same string. That parses the payload twice. If you are going to decode anyway, just call json_decode() with JSON_THROW_ON_ERROR.

Common Pitfalls and Compatibility Notes

  • JSON expects UTF-8. Invalid byte sequences can make encoding or decoding fail. If you are dealing with uncertain input, normalize the text first or use JSON_INVALID_UTF8_SUBSTITUTEwhen encoding.
  • Sparse arrays turn into objects. If you unset an element and leave gaps in the numeric keys, PHP may encode the result as a JSON object. Use array_values() if you need a JSON array.
  • Objects only expose public properties by default. If you are encoding rich domain objects, implement JsonSerializable to control the JSON shape explicitly.
  • Legacy error checks still appear in older codebases. json_last_error() and json_last_error_msg() are still valid, but exception-based handling is cleaner for new work.
  • Version note: json_validate() requires PHP 8.3 or newer. If you support older versions, validate by decoding and handling errors instead.

Libraries Worth Considering

Most PHP projects do not need a third-party library just to format JSON. Libraries become useful when the problem is bigger than formatting, such as mapping nested objects, enforcing serialization rules, or reading huge JSON streams without loading everything into memory.

  • Symfony Serializer: A good fit when you want structured normalization and denormalization between arrays, JSON, and DTOs or entities.
  • JsonMachine: Useful for large JSON documents or API exports because it can stream items instead of decoding the full payload at once.
  • JMS Serializer: Still relevant in projects that already use it for annotation or attribute-driven object serialization.

If your use case is only "format this PHP array as JSON" or "parse this API response," the built-in extension is simpler, faster, and easier to maintain.

Bottom Line

For modern PHP JSON formatting, the default stack is straightforward: use json_encode() with the right flags for readable output, use json_decode() with JSON_THROW_ON_ERROR for safe parsing, and use json_validate() only when you need validation without decoding on PHP 8.3+. Add a library only when you need object mapping or streaming, not for ordinary JSON formatting.

Need help with your JSON?

Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool