Jump to content

Json parsing problem


Texan78

Recommended Posts

Hello, I have ran into a snag for something that is very elementary I am doing. It has been a while since I have worked with json and php so it could just be a simple lapse in memory. 

 

I have a json string I am trying to parse and this is the output of the string, very simple, cut and dry. 

 

 

{"direction":"353.28","latitude":"32.8188024482014","longitude":"-96.6287227224114","active":false,"viewers":0}

 

All I need from that string is the "active" value. 

 

This is the very simple php code I have to parse it, which in the past works great and as outlined later works. 

<?php
$jsonPath = "REMOVED_URL_BUT_GOES_HERE"; // URL to json data

// Lets get and parse the data and create the variables
  $json_string = file_get_contents($jsonPath);
  $parsed_json = json_decode($json_string);
  $status = $parsed_json->active;

  echo $status;

?>

So with the above php code when I echo the variable status, it should return the value as false but, instead I get nothing. 

 

Now as I said I would outline later, to troubleshoot and test if I do echo $json_string; then it outputs the entire string as it should so I know it is getting the contents. For some reason that I am simply overlooking it is not pulling the value for active for the $status variable.

 

What am I missing or overlooking?

 

-Thanks!

Link to comment
https://forums.phpfreaks.com/topic/296267-json-parsing-problem/
Share on other sites

If you do a var_dump() on $status will see is bool(false) false

 

true/false values in json surrounded quotes is a string otherwise is a boolean

 

can check it something like this

if($parsed_json->active == true){
   $status = "true";
}else{
    $status = "false";
}

Or this:

$status = ($parsed_json->active) ? 'true' : 'false';

var_dump() would now be string(5) "false"

Ah that makes perfect sense. I didn't think about the value being a boolean. 

 

Thank you very much for pointing that out. I was able to finish what I was needing to do with that value. 

 

Just to check my work for what I needed it for. Would this be correct? It seems to work and it is light weight. 

if ($status == "true") {
    echo $notify;
}

Meaning that if it is true, display the contents of the $notify variable. 

 

Seems to work through testing. Would this be correct, seeing any problems with that?

 

-Thanks

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.