I have a PHP data structure I want to JSON encode. It can contain a number of empty arrays, some of which need to be encoded as arrays and some of which need to be encoded as objects.
For instance, lets say I have this data structure:
$foo = array( "bar1" => array(), // Should be encoded as an object "bar2" => array() // Should be encoded as an array );
I would like to encode this into:
{ "bar1": {}, "bar2": [] }
But if I use json_encode($foo, JSON_FORCE_OBJECT)
I will get objects as:
{ "bar1": {}, "bar2": {} }
And if I use json_encode($foo)
I will get arrays as:
{ "bar1": [], "bar2": [] }
Is there any way to encode the data (or define the arrays) so I get mixed arrays and objects?
The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.
The json_encode() function is used to encode a value to JSON format.
Parsing JSON data in PHP: There are built-in functions in PHP for both encoding and decoding JSON data. These functions are json_encode() and json_decode(). These functions works only with UTF-8 encoded string. Decoding JSON data in PHP: It is very easy to decode JSON data in PHP.
To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.
Create bar1
as a new stdClass()
object. That will be the only way for json_encode()
to distinguish it. It can be done by calling new stdClass()
, or casting it with (object)array()
$foo = array( "bar1" => new stdClass(), // Should be encoded as an object "bar2" => array() // Should be encoded as an array ); echo json_encode($foo); // {"bar1":{}, "bar2":[]}
OR by typecasting:
$foo = array( "bar1" => (object)array(), // Should be encoded as an object "bar2" => array() // Should be encoded as an array ); echo json_encode($foo); // {"bar1":{}, "bar2":[]}
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