String json to array php

You can convert json Object into Array & String.

$data='{"resultList":[{"id":"1839","displayName":"Analytics","subLine":""},{"id":"1015","displayName":"Automation","subLine":""},{"id":"1084","displayName":"Aviation","subLine":""},{"id":"554","displayName":"Apparel","subLine":""},{"id":"875","displayName":"Aerospace","subLine":""},{"id":"1990","displayName":"Account Reconciliation","subLine":""},{"id":"3657","displayName":"Android","subLine":""},{"id":"1262","displayName":"Apache","subLine":""},{"id":"1440","displayName":"Acting","subLine":""},{"id":"710","displayName":"Aircraft","subLine":""},{"id":"12187","displayName":"AAC","subLine":""}, {"id":"20365","displayName":"AAT","subLine":""}, {"id":"7849","displayName":"AAP","subLine":""}, {"id":"20511","displayName":"AACR2","subLine":""}, {"id":"28585","displayName":"AASHTO","subLine":""}, {"id":"45191","displayName":"AAMS","subLine":""}]}';

$b=json_decode($data);

$i=0;
while($b->{'resultList'}[$i])
{
    print_r($b->{'resultList'}[$i]->{'displayName'});
    echo "
"; $i++; }

(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

7 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

11 months 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);
?>

How can I get JSON encoded data in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

What json_decode () function will return?

Syntax. 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. The values true, false, and null is returned as TRUE, FALSE, and NULL respectively.

Which function converts JSON to array?

Convert JSON to Array Using `json. The parse() function takes the argument of the JSON source and converts it to the JSON format, because most of the time when you fetch the data from the server the format of the response is the string. Make sure that it has a string value coming from a server or the local source.

What is json_decode?

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