today I had to deal with some veeeery strange behaviour of php's json_encode(), that I could nowhere read about.
Encoding it using json_encode()
$obj = new stdClass();
$obj->a = "foo";
$obj->b = "bar";
$obj->c = "doo";
$obj->d = "baa";
json_encode( $obj );
The returned JSON was buggy: a second (the last one, but only this one!) variable was merged with into the string value of the previous one.
For example it looked like:
{"a": "foo", "b": "bar", "c": "doo', 'd': 'baa"}
^-------^
Of course I've var_dumped() the object I'm passing over to json_encode()... nothing! Everything was fine and exactly as expected. All the vars were correct and all the values were strings.
But well, that's not enough. Playing around with that, I found out, that changing the order in wich I'm storing the values into the object solved the problem:
$obj->d = "baa";
$obj->c = "doo";
Did not produce an error.
For now I just changed the order of the columns of the database table. But I would like to know, where this never-seen bug comes from and eventually report it.
The bug only appeared on a Debian-VM running PHP 5.3.6. Another VM running PHP 5.3.3 produced correct JSON, just like Mac OS X Lion's integrated webserver running PHP 5.3.8.
Greetings from Germany!
$obj = new stdClass();
$obj->Id = '35';
$obj->EventsCategories_Id = '8';
$obj->Name = 'Blubber';
$obj->OrderValue = '2';
var_dump($obj);
json_encode($obj);
I have no idea about whether this will help or not, but does running the following code produce any different results?
$obj = new stdClass();
$obj->Id = '35';
$obj->EventsCategories_Id = '8';
$obj->Name = 'Blubber';
$obj->OrderValue = '2';
// convert the stdClass object to an array
$obj = (array) $obj;
var_dump($obj);
json_encode($obj);
I think the pertinent question to ask is whether this is:
While I highly doubt that you've done something wrong (I mean, this is a simple use-case and there's nothing wrong with your code at all), perhaps you could try a couple of other things...
For example, try appending a 2nd argument to the json_encode function:
echo json_encode($obj, JSON_FORCE_OBJECT);
Could you post the results of these two short experiments? This problem is quite strange, indeed. I'm running PHP 5.3.1 and it generates syntactically correct JSON based on your example - no problems to report.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With