JSON to PHP Converter

Convert JSON to PHP arrays or objects online. Preview how PHP will represent any JSON structure, understand json_decode() output, and generate ready-to-use PHP code. Free, no signup required.

json_decode() in PHP: The Complete Guide

PHP has had built-in JSON support since PHP 5.2 through two core functions: json_encode() and json_decode(). Understanding how json_decode() maps JSON types to PHP types is fundamental for any PHP developer working with APIs, configuration, or data storage.

The function signature is:

json_decode(
    string $json,
    bool $associative = false,
    int $depth = 512,
    int $flags = 0
): mixed

The most important parameter is the second one, $associative. When false (the default), JSON objects are returned as stdClass instances. When true, JSON objects are returned as PHP associative arrays. JSON arrays are always returned as PHP indexed arrays regardless of this parameter.

JSON type PHP type (default) PHP type (assoc=true)
stringstringstring
number (int)intint
number (float)floatfloat
booleanboolbool
nullnullnull
objectstdClassarray (associative)
arrayarray (indexed)array (indexed)

Associative Arrays vs stdClass Objects

The choice between associative arrays and stdClass objects is one of the first decisions you make when working with json_decode() in PHP.

stdClass objects are accessed with the arrow operator:

$data = json_decode($json); // returns stdClass
echo $data->name;
echo $data->address->city;
foreach ($data->items as $item) {
    echo $item->price;
}

Associative arrays are accessed with bracket notation and support all PHP array functions:

$data = json_decode($json, true); // returns array
echo $data['name'];
echo $data['address']['city'];
$prices = array_column($data['items'], 'price');
$total = array_sum($prices);

For most PHP applications, associative arrays are the practical choice. They work with array_map, array_filter, array_column, and other standard PHP array functions. Framework libraries like Laravel prefer arrays. Use stdClass only when you need to interoperate with code that explicitly expects objects.

Common json_decode Errors and How to Fix Them

PHP's json_decode() returns null on failure without throwing an exception by default. This silent failure causes many hard-to-debug issues. Here are the most common errors and their solutions:

In PHP 7.3+, the cleanest approach is to always pass JSON_THROW_ON_ERROR:

try {
    $data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    // Handle the specific error
    error_log('JSON decode failed: ' . $e->getMessage());
}

PHP JSON Best Practices

Following these practices ensures reliable and maintainable JSON handling in PHP applications:

Frequently Asked Questions

What does json_decode() return in PHP?

By default, json_decode() returns a stdClass object for JSON objects and a PHP indexed array for JSON arrays. Numbers map to int or float, strings map to string, booleans map to bool, and JSON null maps to PHP null. If the JSON string is invalid, the function returns null and sets a JSON error code retrievable via json_last_error(). Pass true as the second argument to get associative arrays instead of stdClass for all JSON objects.

What is the difference between a PHP associative array and a stdClass object from json_decode?

With the default mode, JSON objects become stdClass and properties are accessed with $obj->key. With the associative mode (json_decode($json, true)), JSON objects become PHP arrays and values are accessed with $arr['key']. Associative arrays integrate naturally with PHP's standard library functions like array_map, array_filter, array_keys, and array_column. Most PHP frameworks and codebases prefer associative arrays for their flexibility and compatibility.

How do I check for json_decode errors in PHP?

After calling json_decode(), use json_last_error() to get the error code and json_last_error_msg() for a human-readable message. Check if (json_last_error() !== JSON_ERROR_NONE) before using the decoded value. In PHP 7.3 and later, the cleanest approach is to pass JSON_THROW_ON_ERROR as the flags parameter, which causes json_decode() to throw a JsonException on failure instead of returning null silently.

What are best practices for working with JSON in PHP?

The most important practice is to use JSON_THROW_ON_ERROR in PHP 7.3+ so invalid JSON never silently returns null and corrupts your application logic. Always set Content-Type: application/json when outputting JSON. Use JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES with json_encode() to produce clean, compact output. In PHP 8.0+ with typed properties, consider using a proper deserialization library like the Symfony Serializer or JMS Serializer to map JSON directly into typed PHP objects instead of working with untyped arrays.

Ready to convert your JSON to PHP?

Free, instant, 100% private. No account needed.

PHP JSON Functions Reference

PHP has excellent built-in support for JSON via json_encode() and json_decode(). Understanding their options is key to building robust PHP APIs.

Core PHP JSON Functions

<?php
$json = '{"id":1,"name":"Alice","active":true}';

// Decode to PHP array (assoc = true)
$array = json_decode($json, true);
echo $array["name"]; // Alice

// Decode to stdClass object
$obj = json_decode($json);
echo $obj->name; // Alice

// Encode PHP array to JSON
$data = ["id" => 1, "name" => "Bob"];
$json = json_encode($data);
// {"id":1,"name":"Bob"}

// Pretty print
$pretty = json_encode($data, JSON_PRETTY_PRINT);

// Error handling
if (json_last_error() !== JSON_ERROR_NONE) {
    echo json_last_error_msg();
}

json_encode() Flags

FlagDescription
JSON_PRETTY_PRINTHuman-readable output with indentation
JSON_UNESCAPED_UNICODEKeep UTF-8 chars as-is (no \uXXXX)
JSON_UNESCAPED_SLASHESDon't escape forward slashes
JSON_THROW_ON_ERRORThrow JsonException instead of returning false
JSON_NUMERIC_CHECKEncode numeric strings as numbers
JSON_FORCE_OBJECTEncode arrays as JSON objects

PHP JSON Best Practices

Also useful: JWT Decoder | JSON Validator | JSON Formatter | JSON to Java | JSON to Go | JSON to C#

How to Parse JSON in PHP — Step by Step

PHP's json_decode() function is the standard way to parse JSON strings into PHP data structures. Here are the two most common patterns along with proper error handling:

<?php
$jsonString = '{"name": "Alice", "age": 30, "city": "London"}';

// Option 1: Parse as associative array (recommended)
$data = json_decode($jsonString, true);
echo $data['name'];  // "Alice"
echo $data['age'];   // 30

// Option 2: Parse as stdClass object
$obj = json_decode($jsonString);
echo $obj->name;  // "Alice"
echo $obj->age;   // 30

// Always check for errors
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new RuntimeException('JSON decode failed: ' . json_last_error_msg());
}
?>

The second argument to json_decode() controls the output type. Passing true returns PHP associative arrays for JSON objects, which integrates directly with PHP's array functions. Omitting it (or passing false) returns stdClass objects accessed with the arrow operator.

PHP JSON Functions Reference

A complete reference of PHP's built-in JSON functions and their most useful options:

Function Description Example
json_decode($str, true) Decode JSON string to PHP array $arr = json_decode($json, true);
json_decode($str) Decode JSON string to stdClass object $obj = json_decode($json);
json_encode($data) Encode PHP value to JSON string $json = json_encode($arr);
json_encode($data, JSON_PRETTY_PRINT) Encode with indentation Pretty-printed output
json_encode($data, JSON_UNESCAPED_UNICODE) Keep Unicode chars as-is Prevents \uXXXX escaping
json_last_error() Get last JSON error code Returns JSON_ERROR_NONE on success
json_last_error_msg() Get last JSON error message Human-readable error string

JSON Type Mapping: JSON to PHP

Understanding how each JSON type maps to a PHP type is essential for writing correct code. The assoc parameter of json_decode() affects only JSON objects:

JSON Type PHP Type Example JSON PHP Result
String string "hello" 'hello'
Number (int) int 42 42
Number (float) float 3.14 3.14
Boolean true bool true true
Boolean false bool false false
null null null null
Array array [1, 2, 3] [1, 2, 3]
Object array (assoc=true) {"a": 1} ['a' => 1]
Object stdClass (assoc=false) {"a": 1} $obj->a === 1

Related Tools

JSON to Python
Generate Python dict or dataclass
JSON to Java
Generate Java POJO classes
JSON to C#
Generate C# classes from JSON
JSON to Ruby
Generate Ruby hashes and classes
JSON Validator
Validate JSON before converting