What is json decode and encode in php?

❮ PHP JSON Reference

Example

Store JSON data in a PHP variable, and then decode it into a PHP object:

$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';

var_dump(json_decode($jsonobj));
?>

Run Example »


Definition and Usage

The json_decode() function is used to decode or convert a JSON object to a PHP object.


Syntax

json_decode(string, assoc, depth, options)

Parameter Values

ParameterDescription
string Required. Specifies the value to be decoded
assoc Optional. Specifies a Boolean value. When set to true, the returned object will be converted into an associative array. When set to false, it returns an object. False is default
depth Optional. Specifies the recursion depth. Default recursion depth is 512
options Optional. Specifies a bitmask (JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR)

Technical Details

Return Value:Returns the value encoded in JSON in appropriate PHP type. If the JSON object cannot be decoded it returns NULL
PHP Version:5.2+
PHP Changelog:PHP 7.3: Added JSON_THROWN_ON_ERROR option
PHP 7.2: Added JSON_INVALID_UTF8_IGNORE, and JSON_INVALID_UTF8_SUBSTITUTE options
PHP 5.4: Added JSON_BIGINT_AS_STRING, and JSON_OBJECT_AS_ARRAY options
PHP 5.4: Added options parameter
PHP 5.3: Added depth parameter

More Examples

Example

Store JSON data in a PHP variable, and then decode it into a PHP associative array:

$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';

var_dump(json_decode($jsonobj, true));
?>

Run Example »

Example

How to access the values from the PHP object:

$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';

$obj = json_decode($jsonobj);

echo $obj->Peter;
echo $obj->Ben;
echo $obj->Joe;
?>

Run Example »

Example

How to access the values from the PHP associative array:

$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';

$arr = json_decode($jsonobj, true);

echo $arr["Peter"];
echo $arr["Ben"];
echo $arr["Joe"];
?>

Run Example »


❮ PHP JSON Reference


(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL json >= 1.2.0)

json_decodeDecodes a JSON string

Description

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

Parameters

json

The json string being decoded.

This function only works with UTF-8 encoded strings.

Note:

PHP implements a superset of JSON as specified in the original » RFC 7159.

associative

When true, JSON objects will be returned as associative arrays; when false, JSON objects will be returned as objects. When null, JSON objects will be returned as associative arrays or objects depending on whether JSON_OBJECT_AS_ARRAY is set in the flags.

depth

Maximum nesting depth of the structure being decoded. The value must be greater than 0, and less than or equal to 2147483647.

flags

Bitmask of JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR. The behaviour of these constants is described on the JSON constants page.

Return Values

Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as true, false and null respectively. null is returned if the json cannot be decoded or if the encoded data is deeper than the nesting limit.

Errors/Exceptions

If depth is outside the allowed range, a ValueError is thrown as of PHP 8.0.0, while previously, an error of level E_WARNING was raised.

Changelog

VersionDescription
7.3.0 JSON_THROW_ON_ERROR flags was added.
7.2.0 associative is nullable now.
7.2.0 JSON_INVALID_UTF8_IGNORE, and JSON_INVALID_UTF8_SUBSTITUTE flags were added.
7.1.0 An empty JSON key ("") can be encoded to the empty object property instead of using a key with value _empty_.

Examples

Example #1 json_decode() examples

$json '{"a":1,"b":2,"c":3,"d":4,"e":5}';var_dump(json_decode($json));
var_dump(json_decode($jsontrue));?>

The above example will output:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

Example #2 Accessing invalid object properties

Accessing elements within an object that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

$json

'{"foo-bar": 12345}';$obj json_decode($json);
print 
$obj->{'foo-bar'}; // 12345?>

Example #3 common mistakes using json_decode()

// the following strings are valid JavaScript but not valid JSON

// the name and value must be enclosed in double quotes
// single quotes are not valid

$bad_json "{ 'bar': 'baz' }";
json_decode($bad_json); // null

// the name must be enclosed in double quotes

$bad_json '{ bar: "baz" }';
json_decode($bad_json); // null

// trailing commas are not allowed

$bad_json '{ bar: "baz", }';
json_decode($bad_json); // null?>

Example #4 depth errors

// Encode some data with a maximum depth  of 4 (array -> array -> array -> string)
$json json_encode(
    array(
        
=> array(
            
'English' => array(
                
'One',
                
'January'
            
),
            
'French' => array(
                
'Une',
                
'Janvier'
            
)
        )
    )
);
// Show the errors for different depths.
var_dump(json_decode($jsontrue4));
echo 
'Last error: 'json_last_error_msg(), PHP_EOLPHP_EOL;var_dump(json_decode($jsontrue3));
echo 
'Last error: 'json_last_error_msg(), PHP_EOLPHP_EOL;
?>

The above example will output:

array(1) {
  [1]=>
  array(2) {
    ["English"]=>
    array(2) {
      [0]=>
      string(3) "One"
      [1]=>
      string(7) "January"
    }
    ["French"]=>
    array(2) {
      [0]=>
      string(3) "Une"
      [1]=>
      string(7) "Janvier"
    }
  }
}
Last error: No error

NULL
Last error: Maximum stack depth exceeded

Example #5 json_decode() of large integers

$json '{"number": 12345678901234567890}';var_dump(json_decode($json));
var_dump(json_decode($jsonfalse512JSON_BIGINT_AS_STRING));?>

The above example will output:

object(stdClass)#1 (1) {
  ["number"]=>
  float(1.2345678901235E+19)
}
object(stdClass)#1 (1) {
  ["number"]=>
  string(20) "12345678901234567890"
}

Notes

Note:

The JSON spec is not JavaScript, but a subset of JavaScript.

Note:

In the event of a failure to decode, json_last_error() can be used to determine the exact nature of the error.

See Also

  • json_encode() - Returns the JSON representation of a value
  • json_last_error() - Returns the last error occurred

Lennart Hengstmengel

8 months ago

JSON can be decoded to PHP arrays by using the $associative = true option. Be wary that associative arrays in PHP can be a "list" or "object" when converted to/from JSON, depending on the keys (of absence of them).

You would expect that recoding and re-encoding will always yield the same JSON string, but take this example:

    $json = '{"0": "No", "1": "Yes"}';
    $array = json_decode($json, true);  // decode as associative hash
    print json_encode($array) . PHP_EOL;

This will output a different JSON string than the original:

    ["No","Yes"]

The object has turned into an array!

Similarly, a array that doesn't have consecutive zero based numerical indexes, will be encoded to a JSON object instead of a list.

    $array = [
        'first',
        'second',
        'third',
    ];
    print json_encode($array) . PHP_EOL;
    // remove the second element
    unset($array[1]);
    print json_encode($array) . PHP_EOL;

The output will be:

    ["first","second","third"]
    {"0":"first","2":"third"}

The array has turned into an object!

In other words, decoding/encoding to/from PHP arrays is not always symmetrical, or might not always return what you expect!

On the other hand, decoding/encoding from/to stdClass objects (the default) is always symmetrical.

Arrays may be somewhat easier to work with/transform than objects. But especially if you need to decode, and re-encode json, it might be prudent to decode to objects and not arrays.

If you want to enforce an array to encode to a JSON list (all array keys will be discarded), use:

    json_encode(array_values($array));

If you want to enforce an array to encode to a JSON object, use:

    json_encode((object)$array);

See also: https://www.php.net/manual/en/function.array-is-list.php

Alien426

1 year ago

Browsers don't choke on integers _starting_ with BigInt (64 bits), but before that (53 bits). The introduction of BigInt to modern browsers doesn't help much, when JSON handling functions do not support it. So I am trying to remedy that. My approach is to handle the decoded array before re-encoding it to a string:
function fix_large_int(&$value)
{
  if (
is_int($value) && $value > 9007199254740991)
   
$value = strval($value);
}
$json_str = '{"id":[1234567890123456789,12345678901234567890]}';
$json_arr = json_decode($json_str, flags: JSON_BIGINT_AS_STRING | JSON_OBJECT_AS_ARRAY);
echo(
json_encode($json_arr)); // {"id":[1234567890123456789,"12345678901234567890"]} (BigInt is already converted to a string here)
array_walk_recursive($json_arr, 'fix_large_int');
echo(
json_encode($json_arr)); // {"id":["1234567890123456789","12345678901234567890"]}
?>

cubefox at web dot NOSPAMPLEASE dot de

1 year ago

Warning: As the section "return values" mentions, the return value NULL is ambiguos. To repeat, it can mean three things:

* The input string had the value "null"
* There was an error while parsing the input data
* The encoded data was deeper than the recursion limit

To distinguish these cases, json_last_error() can be used.

greaties at ghvernuft dot nl

1 year ago

To load an object with data in json format:

function loadJSON($Obj, $json)
{
    $dcod = json_decode($json);
    $prop = get_object_vars ( $dcod );
    foreach($prop as $key => $lock)
    {
        if(property_exists ( $Obj ,  $key ))
        {
            if(is_object($dcod->$key))
            {
                loadJSON($Obj->$key, json_encode($dcod->$key));
            }
            else
            {
                $Obj->$key = $dcod->$key;
            }
        }
    }
}

as-works at narod dot ru

10 months ago

On some PHP7+ systems php_json functions can be undefined (i faced it on Oracle Linux Enterprice with php 7.4 installed from REMI repository). If you have the same problem, try to install separated php-json module:

# yum install php-json

Hope this helps.

Anonymous

1 year ago

$array

= [0 => "foo", 1 => "bar", 2 => ["baz"]];$associative = false;var_dump(
   
json_decode(
       
json_encode($array),
       
$associative
   
)
);
?>

The above will output
/*
array (size=3)
  0 => string 'foo' (length=3)
  1 => string 'bar' (length=3)
  2 =>
    array (size=1)
      0 => string 'baz' (length=3)
*/
?>

Considering = false; ?> one might expect
/*
object(stdClass)
  public '0' => string 'foo' (length=3)
  public '1' => string 'bar' (length=3)
  public '2' =>
    object(stdClass)
      public '0' => string 'baz' (length=3)
*/
?>

an stdClass object instead of an array, but this is incorrect.
json_decode will always return an array for a sequentially encoded array, regardless of the ?bool $associative 2nd argument

Which is inline with the above mentioned docs/spec
    > Returns the value encoded in json in appropriate PHP type

Considering that the 1st arg was a sequentially encoded array as a json string
    '["foo","bar",["baz"]]'

mattia

1 year ago

if you're using ajax to post, and your JavaScript code looks like this:


    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "something.php", true);
    xhttp.setRequestHeader("Content-Type", "application/json");
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
             // do something
        }
    };
    var data = {some: "thing"};
    xhttp.send(JSON.stringify(data));

then in something.php you can retrieve your json by doing

$data = json_decode(file_get_contents("php://input"), true);
?>

What is JSON encoding and decoding?

JsonEncoder and JsonDecoder​ A decoder is a function that takes a CharSequence and returns a Right with the decoded value or a Left with an error message. An encoder is a function that takes a value of type A and returns a CharSequence that represents the encoded value (JSON string).

What is JSON encode in PHP?

json_encode() is a native PHP function that allows you to convert PHP data into the JSON format. json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] ) : string. The function takes in a PHP object ($value) and returns a JSON string (or False if the operation fails).

What is JSON decoding?

The json_decode() function is used to decode or convert a JSON object to a PHP object.

What is JSON encoding?

jsonencode encodes a given value to a string using JSON syntax. The JSON encoding is defined in RFC 7159. This function maps Terraform language values to JSON values in the following way: Terraform type. JSON type.