Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP JSon How to read boolean value received in JSon format and write in string on PHP

Tags:

json

php

I receive this JSON string from another site and I cannot modify what received from. The string is receive in $_POST and is :

[
    {
        "clientId":"17295c59-4373-655a-1141-994aec1779dc",
        "channel":"\/meta\/connect",
        "connectionType":"long-polling",
        "ext":{
            "fm.ack":false,
            "fm.sessionId":"22b0bdcf-4a35-62fc-3764-db4caeece44b"
        },
        "id":"5"
    }
]

I decode the JSON string with the following code :

$receive = json_decode(file_get_contents('php://input'));

And when I use print_r($receive) I get the following:

Array (
[0] => stdClass Object
    (
        [clientId] => 17295c59-4373-655a-1141-994aec1779dc
        [channel] => /meta/connect
        [connectionType] => long-polling
        [ext] => stdClass Object
            (
                [fm.ack] => 
                [fm.sessionId] => 22b0bdcf-4a35-62fc-3764-db4caeece44b
            )

        [id] => 5
    )
)

I can access and read all Array / Object with no problem :

$receive[$i]->clientId;
$receive[$i]->channel;
$connectionType = $receive[$i]->connectionType;
$receive[$i]->id;
$receive[$i]->ext->{'fm.sessionId'};

But {fm.ack} is empty

In the decoded JSON string, the false value is not between "".

Is it possible to access and read the false value and convert it into string value instead?

Thank you for your helping !

like image 301
LiTHiUM2525 Avatar asked Feb 26 '13 04:02

LiTHiUM2525


2 Answers

you can use it like this, in JSON format when you evaluate false value it will give you blank, and when you evaluate true it will give you 1.

$str = '[{"clientId":"17295c59-4373-655a-1141-994aec1779dc","channel":"\/meta\/connect","connectionType":"long-polling","ext":{"fm.ack":false,"fm.sessionId":"22b0bdcf-4a35-62fc-3764-db4caeece44b"},"id":"5"}]';

$arr = json_decode($str,true);

if($arr[0]['ext']['fm.ack'])    // suggested by **mario**
{
    echo "true";    
}
else {
    echo "false";   
}
like image 158
Yogesh Suthar Avatar answered Oct 04 '22 21:10

Yogesh Suthar


I know there is already an answer to this but it may be worth noting that var_dump outputs Boolean values better it just has worse formatting IMO.

<pre>
    <?php
        print_r(array(true, false));
        var_dump(array(true, false));
    ?>
</pre>

Results in

Array
(
    [0] => 1
    [1] => 
)
array(2) {
  [0]=>
  bool(true)
  [1]=>
  bool(false)
}
like image 27
Christian Avatar answered Oct 04 '22 21:10

Christian