Object of class stdClass could not be converted to string error

前端 未结 6 1185
一生所求
一生所求 2021-01-05 00:12

I have the following string:

{\"Coords\":[{\"Accuracy\":\"65\",\"Latitude\":\"53.277720488429026\",\"Longitude\":\"-9.012038778269686\",\"Timestamp\":\"Fri J         


        
6条回答
  •  庸人自扰
    2021-01-05 00:23

    You get the error because you are trying to turn a stdClass object into a string, something it doesn't support.

    Instead of echo $decoded_traces try var_dump($decoded_traces) - that will give a diagnostic view of the object you've decoded (which I presume is what you wanted). You should find it looks like this

    class stdClass#1 (2) {
      public $Coords =>
      array(5) {
        [0] =>
        class stdClass#2 (4) {
          public $Accuracy =>
          string(2) "65"
          public $Latitude =>
          string(18) "53.277720488429026"
          public $Longitude =>
          string(18) "-9.012038778269686"
          public $Timestamp =>
          string(39) "Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"
        }
        [1] => (more of the same, edited for brevity)
        [2] =>
        [3] =>
        [4] =>
      }
      public $Scan =>
      string(8) "Whatever"
    }
    

    By default, json_encode will create stdClass objects like the above. If you would prefer an associative array, pass true as the second parameter to json_decode, e.g. $decoded_traces=json_decode($traces, true);

    As a further aside, although stdClass can't be turned into a string, your own classes can - a class which implements the __toString magic method could be converted to a string!

提交回复
热议问题