user2635961
user2635961

Reputation: 379

Decoding JSON string in PHP which has different headers

I am trying to decode a series of JSON messages

The JSON messgaes are received on an adhoc basis

If the JSON messages were all exactly the same format I would be fine. However they are not.

Here is an example of two different types.

   object(stdClass)#11 (1) { ["SF_MSG"]=> object(stdClass)#12 (5) { ["time"]=>      string(13) "1407962618000" ["area_id"]=> string(2) "NM" ["address"]=> string(2) "2B" ["msg_type"]=> string(2) "SF" ["data"]=> string(2) "FE" } } 

   object(stdClass)#13 (1) { ["CA_MSG"]=> object(stdClass)#14 (5) { ["to"]=> string(4) "0360" ["time"]=> string(13) "1407962618000" ["area_id"]=> string(2) "WH" ["msg_type"]=> string(2) "CC" ["descr"]=> string(4) "2S30" } } 

One has a header of SF_MSG and the other CC_MSG

My question is "How do I in PHP distinguish between the different headers so I can read them in different ways

So for example echo '$Decodedjson->SF_MSG->time; will echo the time on the first one and echo $Decodedjson->CC_MSG->to; will echo the to variable. However I need to know whether the header is SF_MSG or a CC_MSG before performing that task.

How do I read that Header title????? ie is it CC_MSG or SF_MSG ......$Decodedjson->?????

Thanks

EDIT

              if ($con->hasFrame()){
              $msg=$con->readFrame();
              foreach (json_decode($msg->body) as $event) {

              if(isset($event['SFG_MSG'])) {
              $aid=($event->SF_MSG->area_id);
              }
              elseif(isset($event['CA_MSG'])) {
              $aid=($event->CA_MSG->area_id);
              }

              echo $aid;

Upvotes: 1

Views: 376

Answers (1)

hofan41
hofan41

Reputation: 1468

json_decode() requires true as the second parameter in order for the resultant object to be an associative array.

foreach (json_decode($msg->body, true) as $event)

once you do this, $event will be an associative array and no longer an object, so you will need to change the rest of your code to access $event as an array instead of an object.

 // this won't work
 $aid=($event->SF_MSG->area_id);

 // change to this
 $aid = $event["SF_MSG"]["area_id"];

Upvotes: 2

Related Questions