Question

PHP json_decode(): Decode JSON as an Associative Array

phparraysjson

Question

How can I decode JSON into a PHP associative array instead of an object? My current code produces this error:

Fatal error: Cannot use object of type stdClass as array
$jsonUrl = 'http://www.example.com/jsondata.json';

$jsonData = file_get_contents($jsonUrl);
$obj = json_decode($jsonData);

print_r($obj['Result']);

Why does this happen, and how should I access the Result value as an array?

Short Answer

By the end of this page, you will understand why json_decode() returns a stdClass object by default, how to request an associative array, and how to safely validate and access decoded JSON data in PHP.

Concept

json_decode() converts a JSON string into a PHP value.

A JSON object uses curly braces:

{
  "Result": "success",
  "count": 3
}

By default, PHP converts JSON objects into instances of stdClass, a generic PHP object:

$data = json_decode($json);

That means its properties must be read with object syntax:

echo $data->Result;

The error occurs because this code uses array syntax:

$obj['Result']

Square brackets work only with arrays. They do not work with a stdClass object.

If you want PHP associative arrays instead, pass true as the second argument to json_decode():

$data = json_decode($json, true);

Now JSON objects become PHP associative arrays, so this works:

print_r($data['Result']);

Choosing consistently between objects and arrays matters because it makes API responses, configuration files, and stored JSON predictable throughout your application.

Mental Model

Think of decoded JSON as a set of labeled storage containers.

  • An object is like a filing cabinet: open a drawer using its label with ->.
    $data->Result
    
  • An associative array is like a dictionary: look up an entry using a key in square brackets.
    $data['Result']
    

Both can represent the same JSON data. The important rule is to use the access style that matches the type you received.

Take Quiz

Syntax and Examples

Use the second argument of json_decode() to choose whether JSON objects become associative arrays.

json_decode(string $json, bool|null $associative = null): mixed

Decode JSON as an object (default)

$json = '{"Result":"success","count":3}';

$data = json_decode($json);

echo $data->Result; // success
echo $data->count;  // 3

Decode JSON as an associative array

$json = '{"Result":"success","count":3}';

$data = json_decode($json, true);

echo $data['Result']; // success
echo $data['count'];  // 3

Corrected version of the original code

$jsonUrl = 'http://www.example.com/jsondata.json';

$jsonData = file_get_contents($jsonUrl);
$data = json_decode($jsonData, true);

print_r($data['Result']);

With true, every JSON object at every nesting level is decoded as an associative array. JSON lists, written with square brackets ([]), are decoded as normal indexed PHP arrays either way.

Step by Step Execution

Consider this JSON response:

$json = '{"Result":{"status":"ok","items":["pen","book"]}}';

Decode it as an associative array:

$data = json_decode($json, true);

$status = $data['Result']['status'];
$firstItem = $data['Result']['items'][0];

echo $status;
echo $firstItem;

Step by step:

  1. $json contains text in JSON format.
  2. json_decode($json, true) converts the outer JSON object into a PHP array.
  3. The Result key contains another JSON object, which also becomes an associative array.
  4. status is read with ['status'].
  5. items is a JSON list, so it becomes an indexed PHP array.
  6. Index 0 accesses the first item, pen.

The output is:

okpen

In real code, add spaces or line breaks when displaying separate values.

Real World Use Cases

Decoding JSON as associative arrays is common when your code already works heavily with PHP arrays.

  • API responses: Read a weather API response with $weather['current']['temperature'].
  • Configuration files: Load JSON settings such as $config['database']['host'].
  • Form or webhook payloads: Inspect incoming data and validate required keys.
  • Data imports: Loop through a JSON list of products, orders, or users.
  • Command-line scripts: Decode JSON output from another command and process fields by key.

For example, processing products returned by an API:

$json = '[{"name":"Keyboard","price":49.99},{"name":"Mouse","price":19.99}]';
$products = json_decode($json, true);

foreach ($products as $product) {
    echo $product['name'] . ': $' . $product['price'] . PHP_EOL;
}
Take Quiz

Real Codebase Usage

In production code, decoding JSON is usually paired with error handling and validation.

Prefer exceptions for invalid JSON

JSON_THROW_ON_ERROR makes malformed JSON fail immediately with a JsonException instead of silently returning null.

try {
    $data = json_decode($jsonData, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
    error_log('Invalid JSON: ' . $exception->getMessage());
    $data = [];
}

Use guard clauses before accessing required data

$data = json_decode($jsonData, true, 512, JSON_THROW_ON_ERROR);

if (!isset($data['Result'])) {
    throw new RuntimeException('Response does not contain a Result field.');
}

$result = $data['Result'];

Check an HTTP request before decoding its body

file_get_contents() can fail and return false. Avoid sending that failure value directly to the JSON decoder.

$jsonData = file_get_contents($jsonUrl);

if ($jsonData === false) {
    throw new RuntimeException('Unable to retrieve JSON data.');
}

$data = json_decode($jsonData, true, 512, JSON_THROW_ON_ERROR);

Many modern PHP projects use an HTTP client rather than file_get_contents() because it provides status codes, timeouts, headers, and clearer error reporting. The JSON decoding rule remains the same: choose arrays or objects deliberately and access them consistently.

Common Mistakes

Using array syntax on the default decoded object

This causes the error in the question:

$data = json_decode('{"Result":"success"}');
echo $data['Result']; // Error: stdClass cannot be used as an array

Fix it by either using object syntax:

echo $data->Result;

Or decoding as an array:

$data = json_decode('{"Result":"success"}', true);
echo $data['Result'];

Using object syntax after requesting an array

$data = json_decode('{"Result":"success"}', true);
echo $data->Result; // Warning/error: array access must use brackets

Use this instead:

echo $data['Result'];

Ignoring invalid JSON

Malformed JSON normally causes json_decode() to return null.

$data = json_decode('{"Result": }', true);

Use JSON_THROW_ON_ERROR so failures are explicit:

$data = json_decode('{"Result": }', true, 512, JSON_THROW_ON_ERROR);

Assuming a key always exists

An API may omit a field or return an error response with a different shape.

// Risky if Result is absent.
echo $data['Result'];

Check first:

if (isset($data['Result'])) {
    echo $data['Result'];
}

Confusing JSON objects with JSON arrays

A JSON object has named properties:

{"name":"Ada"}

A JSON array is an ordered list:

["Ada", "Linus"]

When decoding with true, both are PHP arrays, but one is keyed by names and the other by numeric indexes.

Comparisons

ChoiceDecode codeAccess a Result valueBest when
Default objectjson_decode($json)$data->ResultYou prefer property-style access or work with objects already.
Associative arrayjson_decode($json, true)$data['Result']Your application uses array functions and bracket notation.
Throw on invalid JSONjson_decode($json, true, 512, JSON_THROW_ON_ERROR)$data['Result']You need reliable error handling in production code.

-> versus []

SyntaxWorks withExample
->propertyObjects, including stdClass$user->name
['key']Associative arrays$user['name']
[0]Indexed arrays$items[0]

Arrays are particularly convenient with functions such as array_map(), array_filter(), and array_column(). Objects can be useful when code is designed around classes and properties. Neither decoding style is universally better; consistency is what prevents access errors.

Take Quiz

Cheat Sheet

// JSON object -> stdClass object (default)
$data = json_decode($json);
echo $data->Result;

// JSON object -> associative array
$data = json_decode($json, true);
echo $data['Result'];

// Recommended when invalid JSON must fail clearly
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
  • JSON {} becomes stdClass by default.
  • Pass true to make JSON objects associative arrays.
  • Use -> for objects.
  • Use ['key'] for associative arrays.
  • JSON lists [] become indexed PHP arrays.
  • Check that downloads succeed before decoding them.
  • Use JSON_THROW_ON_ERROR for dependable JSON error handling.
  • Verify optional keys with isset($data['key']) before reading them.

FAQ

Why does json_decode() return stdClass?

PHP decodes JSON objects into stdClass objects by default. This lets you access JSON properties with ->.

How do I make json_decode() return an associative array?

Pass true as the second argument:

$data = json_decode($json, true);

Should I use objects or associative arrays for JSON in PHP?

Either is valid. Choose arrays when your code uses bracket access and PHP array functions. Choose objects when property access is clearer. Do not mix their access syntax.

What does the second argument of json_decode() do?

It controls how JSON objects are decoded. true produces associative arrays; the default produces stdClass objects.

What happens if the JSON is invalid?

Without special flags, json_decode() usually returns null. Use JSON_THROW_ON_ERROR to receive a JsonException instead.

Does json_decode($json, true) convert JSON lists too?

JSON lists already decode to PHP indexed arrays. The true argument mainly changes JSON objects from stdClass objects to associative arrays.

How can I safely access a possibly missing JSON key?

Use isset() when a missing value should be ignored or handled differently:

if (isset($data['Result'])) {
    echo $data['Result'];
}
Take Quiz

Mini Project

Description

Build a small JSON response reader for a fictional task API. The script retrieves JSON text, decodes it as an associative array, validates the expected structure, and prints each task. This mirrors the basic processing that many integrations perform after receiving an API response.

Goal

Decode a JSON task response safely and display the completed task titles.

Requirements

Use json_decode() to decode the JSON as an associative array. Validate that the top-level tasks key exists and contains an array. Loop through every task. Display only tasks whose completed value is true. Use JSON_THROW_ON_ERROR to handle invalid JSON.

Take Quiz

Keep learning

Related questions

View more