Based on provided input - you must replace all those nasty backslashes and double quotes in order to get proper JSON:

Copy<?php
$s = '{
    "key1": "value1",
    "key2": "{\"key3\":\"{\\\"key4\\\":\\\"value4\\\"}\"}"
}';

$s = str_replace('\\', '', $s);
$s = str_replace('"{', '{', $s);
$s = str_replace('}"', '}', $s);

print_r(json_decode($s, true));
?>

Output:

CopyArray
(
[key1] => value1
[key2] => Array
    (
        [key3] => Array
            (
                [key4] => value4
            )
    )
)
Answer from mitkosoft on Stack Overflow
🌐
Tutorialspoint
tutorialspoint.com › php › php_function_javascript_object_notation_json_decode.htm
JSON Decode in PHP
The json_decode() function can decode a JSON string. The json_decode() function can take a JSON encoded string and convert into a PHP variable. The json_decode() function can return a value encoded in JSON in appropriate PHP type.
🌐
FlatCoding
flatcoding.com › home › php json handling with json_encode & json_decode
PHP JSON Handling with json_encode & json_decode - FlatCoding
April 15, 2025 - Anyway, in the following section, you will learn how to decode JSON data with json_decode(). We have seen how to encode data, let’s take a look at the reverse process—called decoding. PHP’s json_decode() function takes a JSON string and converts it back into a PHP data structure.
Discussions

How can I decode in PHP a json string that has a json string as a value inside? - Stack Overflow
The other end gives me a big json ... and put into a string. The rest of the JSON is a usual JSON structure but one of the value is the json encoded receipt put as a string value. I have to decode everything before processing it properly. ... What you have posted is not valid JSON. It would be valid JSON if all the PHP was removed ... More on stackoverflow.com
🌐 stackoverflow.com
Encoding/Decoding JSON PHP - PHP - SitePoint Forums | Web Development & Design Community
Can someone please help out here? I have this string in my PHP file and I can not figure out how to parse this. I have tried a million iterations of json_decode and json_encode and stripslashes. I am just trying to acces… More on sitepoint.com
🌐 sitepoint.com
0
February 19, 2023
How to extract and access data from JSON with PHP? - Stack Overflow
This is intended to be a general reference question and answer covering many of the never-ending "How do I access data in my JSON?" questions. It is here to handle the broad basics of decoding JSON in PHP and accessing the results. More on stackoverflow.com
🌐 stackoverflow.com
Parsing JSON object in PHP using json_decode - Stack Overflow
If you set the second parameter of json_decode to true, you get an array, so you cant use the -> syntax. I would also suggest you install the JSONview Firefox extension, so you can view generated json documents in a nice formatted tree view similiar to how Firefox displays XML structures. More on stackoverflow.com
🌐 stackoverflow.com
🌐
PHP
php.net › manual › en › function.json-decode.php
PHP: json_decode - Manual
Takes a JSON encoded string and converts it into a PHP value. ... The json string being decoded.
🌐
W3Schools
w3schools.com › php › func_json_decode.asp
PHP json_decode() Function
json_decode() json_encode() json_last_error() PHP Keywords · abstract and as break callable case catch class clone const continue declare default do echo else elseif empty enddeclare endfor endforeach endif endswitch endwhile extends final finally fn for foreach function global if implements include ...
🌐
Tutorial Republic
tutorialrepublic.com › php-tutorial › php-json-parsing.php
How to Encode and Decode JSON Data in PHP - Tutorial Republic
The following example demonstrates how to decode or convert a JSON object to PHP object. ... <?php // Store JSON data in a PHP variable $json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}'; var_dump(json_decode($json)); ?>
Find elsewhere
🌐
Envato Tuts+
code.tutsplus.com › home › cloud & hosting
How to Parse JSON in PHP | Envato Tuts+
May 31, 2021 - First, you need to get the data from the file into a variable by using file_get_contents(). Once the data is in a string, you can call the json_decode() function to extract information from the string.
🌐
SitePoint
sitepoint.com › php
Encoding/Decoding JSON PHP - PHP - SitePoint Forums | Web Development & Design Community
February 19, 2023 - Can someone please help out here? I have this string in my PHP file and I can not figure out how to parse this. I have tried a million iterations of json_decode and json_encode and stripslashes. I am just trying to acces…
🌐
ReqBin
reqbin.com › code › php › zg4d50d8 › php-json-decode-example
How do I decode JSON in PHP?
July 7, 2023 - To decode a JSON string or file in PHP, you can use the json_decode($json, $assoc, $depth, $options) function. The first parameter specifies the string to be decoded. The second optional parameter sets whether the returned object should be converted ...
🌐
OnlinePHP
onlinephp.io › json-decode
json_decode - Online Tool
PHP Functions · General · json_decode · Execute json_decode with this online tool json_decode() - Decodes a JSON string · Json Decode Online Tool · Manual · Code Examples · Json Decode Online Tool · Manual · Code Examples · hex2bin ...
🌐
GeeksforGeeks
geeksforgeeks.org › php › php-json_decode-function
PHP | json_decode() Function - GeeksforGeeks
July 11, 2025 - The json_decode() function is an inbuilt function in PHP which is used to decode a JSON string. It converts a JSON encoded string into a PHP variable.
Top answer
1 of 3
610

Intro

First off you have a string. JSON is not an array, an object, or a data structure. JSON is a text-based serialization format - so a fancy string, but still just a string. Decode it in PHP by using json_decode().

 $data = json_decode($json);

Therein you might find:

  • scalars: strings, ints, floats, and bools
  • nulls (a special type of its own)
  • compound types: objects and arrays.

These are the things that can be encoded in JSON. Or more accurately, these are PHP's versions of the things that can be encoded in JSON.

There's nothing special about them. They are not "JSON objects" or "JSON arrays." You've decoded the JSON - you now have basic everyday PHP types.

Objects will be instances of stdClass, a built-in class which is just a generic thing that's not important here.


Accessing object properties

You access the properties of one of these objects the same way you would for the public non-static properties of any other object, e.g. $object->property.

$json = '
{
    "type": "donut",
    "name": "Cake"
}';

$yummy = json_decode($json);

echo $yummy->type; //donut

Accessing array elements

You access the elements of one of these arrays the same way you would for any other array, e.g. $array[0].

$json = '
[
    "Glazed",
    "Chocolate with Sprinkles",
    "Maple"
]';

$toppings = json_decode($json);

echo $toppings[1]; //Chocolate with Sprinkles

Iterate over it with foreach.

foreach ($toppings as $topping) {
    echo $topping, "\n";
}

Glazed
Chocolate with Sprinkles
Maple

Or mess about with any of the bazillion built-in array functions.


Accessing nested items

The properties of objects and the elements of arrays might be more objects and/or arrays - you can simply continue to access their properties and members as usual, e.g. $object->array[0]->etc.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

echo $yummy->toppings[2]->id; //5004

Passing true as the second argument to json_decode()

When you do this, instead of objects you'll get associative arrays - arrays with strings for keys. Again you access the elements thereof as usual, e.g. $array['key'].

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json, true);

echo $yummy['toppings'][2]['type']; //Maple

Accessing associative array items

When decoding a JSON object to an associative PHP array, you can iterate both keys and values using the foreach (array_expression as $key => $value) syntax, eg

$json = '
{
    "foo": "foo value",
    "bar": "bar value",
    "baz": "baz value"
}';

$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
    echo "The value of key '$key' is '$value'", PHP_EOL;
}

Prints

The value of key 'foo' is 'foo value'
The value of key 'bar' is 'bar value'
The value of key 'baz' is 'baz value'


Don't know how the data is structured

Read the documentation for whatever it is you're getting the JSON from.

Look at the JSON - where you see curly brackets {} expect an object, where you see square brackets [] expect an array.

Hit the decoded data with a print_r():

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

print_r($yummy);

and check the output:

stdClass Object
(
    [type] => donut
    [name] => Cake
    [toppings] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 5002
                    [type] => Glazed
                )

            [1] => stdClass Object
                (
                    [id] => 5006
                    [type] => Chocolate with Sprinkles
                )

            [2] => stdClass Object
                (
                    [id] => 5004
                    [type] => Maple
                )

        )

)

It'll tell you where you have objects, where you have arrays, along with the names and values of their members.

If you can only get so far into it before you get lost - go that far and hit that with print_r():

print_r($yummy->toppings[0]);
stdClass Object
(
    [id] => 5002
    [type] => Glazed
)

Take a look at it in this handy interactive JSON explorer.

Break the problem down into pieces that are easier to wrap your head around.


json_decode() returns null

This happens because either:

  1. The JSON consists entirely of just that, null.
  2. The JSON is invalid - check the result of json_last_error_msg or put it through something like JSONLint.
  3. It contains elements nested more than 512 levels deep. This default max depth can be overridden by passing an integer as the third argument to json_decode().

If you need to change the max depth you're probably solving the wrong problem. Find out why you're getting such deeply nested data (e.g. the service you're querying that's generating the JSON has a bug) and get that to not happen.


Object property name contains a special character

Sometimes you'll have an object property name that contains something like a hyphen - or at sign @ which can't be used in a literal identifier. Instead you can use a string literal within curly braces to address it.

$json = '{"@attributes":{"answer":42}}';
$thing = json_decode($json);

echo $thing->{'@attributes'}->answer; //42

If you have an integer as property see: How to access object properties with names like integers? as reference.


Someone put JSON in your JSON

It's ridiculous but it happens - there's JSON encoded as a string within your JSON. Decode, access the string as usual, decode that, and eventually get to what you need.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": "[{ \"type\": \"Glazed\" }, { \"type\": \"Maple\" }]"
}';

$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);

echo $toppings[0]->type; //Glazed

Data doesn't fit in memory

If your JSON is too large for json_decode() to handle at once things start to get tricky. See:

  • Processing large JSON files in PHP
  • How to properly iterate through a big json file

How to sort it

See: Reference: all basic ways to sort arrays and data in PHP.

2 of 3
5
<?php
$jsonData = '{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

// Decode the JSON
$data = json_decode($jsonData, true);

// Access the data
$type = $data['type'];
$name = $data['name'];
$toppings = $data['toppings'];

// Access individual topping details
$firstTopping = $toppings[0];
$firstToppingId = $firstTopping['id'];
$firstToppingType = $firstTopping['type'];

// Print the data
echo "Type: $type\n";
echo "Name: $name\n";
echo "First Topping ID: $firstToppingId\n";
echo "First Topping Type: $firstToppingType\n";
?>

In this example, json_decode() is used to decode the JSON data into a PHP associative array. You can then access the individual elements of the array as you would with any PHP array.

🌐
W3Schools
w3schools.com › php › php_json.asp
PHP and JSON
json_decode() json_encode() json_last_error() PHP Keywords · abstract and as break callable case catch class clone const continue declare default do echo else elseif empty enddeclare endfor endforeach endif endswitch endwhile extends final finally fn for foreach function global if implements include ...
🌐
W3Schools
w3schools.com › js › js_json_php.asp
JSON PHP
Convert the request into an object, using the PHP function json_decode().
🌐
GeeksforGeeks
geeksforgeeks.org › php › how-to-parse-a-json-file-in-php
How to parse a JSON File in PHP? - GeeksforGeeks
'my_data.json' is the file name. It works if the file is in the same folder as the PHP script, or you need to specify the correct path if it's elsewhere. The json_decode() function is used to convert the JSON string into a PHP array or object.
Published   June 24, 2025