Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP json_decode return empty array

Tags:

json

php

decode

I just test this sample from php doc (https://www.php.net/manual/en/function.json-decode.php)

here is my code:

<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; echo json_decode($json, true), '<br />';?>

But it just returns an EMPTY array.

Have no idea why...Been searching around but no solution found.

PLEASE help!

like image 376
user3705546 Avatar asked Nov 30 '25 03:11

user3705546


2 Answers

You can validate at following website: http://jsonlint.com/

You have to use a php "json_decode()" function to decode a json encoded data. Basically json_decode() function converts JSON data to a PHP array.

Syntax: json_decode( data, dataTypeBoolean, depth, options )

data : - The json data that you want to decode in PHP.

dataTypeBoolean(Optional) :- boolean that makes the function return a PHP Associative Array if set to "true", or return a PHP stdClass object if you omit this parameter or set it to "false". Both data types can be accessed like an array and use array based PHP loops for parsing.

depth :- Optional recursion limit. Use an integer as the value for this parameter.

options :- Optional JSON_BIGINT_AS_STRING parameter.

Now Comes to your Code

$json_string = '{"a":1,"b":2,"c":3,"d":4,"e":5}' ;

Assign a valid json data to a variable $json_string within single quot's ('') as json string already have double quots.

// here i am decoding a json string by using a php 'json_decode' function, as mentioned above & passing a true parameter to get a PHP associative array otherwise it will bydefault return a PHP std class objecy array.

$json_decoded_data = json_decode($json_string, true);

// just can check here your encoded array data.
// echo '<pre>';
// print_r($json_decoded_data);

// loop to extract data from an array
foreach ($json_decoded_data as $key => $value) {
    echo "$key | $value <br/>";

}
like image 86
Aksh Avatar answered Dec 02 '25 17:12

Aksh


you should not use echo because it is an array. use print_r or var_dump .it works fine

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
print_r(json_decode($json, true));

Output:

Array
(
   [a] => 1
   [b] => 2
   [c] => 3
   [d] => 4
   [e] => 5
)
like image 25
MH2K9 Avatar answered Dec 02 '25 18:12

MH2K9



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!