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():
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.
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'];
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:
$jsoncontains text in JSON format.json_decode($json, true)converts the outer JSON object into a PHP array.- The
Resultkey contains another JSON object, which also becomes an associative array. statusis read with['status'].itemsis a JSON list, so it becomes an indexed PHP array.- Index
0accesses the first item, .
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;
}
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.');
}
= [];
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:
[];
Comparisons
| Choice | Decode code | Access a Result value | Best when |
|---|---|---|---|
| Default object | json_decode($json) | $data->Result | You prefer property-style access or work with objects already. |
| Associative array | json_decode($json, true) | $data['Result'] | Your application uses array functions and bracket notation. |
| Throw on invalid JSON | json_decode($json, true, 512, JSON_THROW_ON_ERROR) | $data['Result'] | You need reliable error handling in production code. |
-> versus []
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
{}becomesstdClassby default. - Pass
trueto 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_ERRORfor 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 instead.
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.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.