Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP json_encode - JSON_FORCE_OBJECT mixed object and array output

Tags:

json

php

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?

like image 811
Woodgnome Avatar asked Jul 26 '12 13:07

Woodgnome


People also ask

What does json_encode return?

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.

What does the PHP function json_encode () do?

The json_encode() function is used to encode a value to JSON format.

What is json_encode and Json_decode in PHP?

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.

How can I get JSON encoded 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.


1 Answers

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":[]} 
like image 129
Michael Berkowski Avatar answered Oct 03 '22 12:10

Michael Berkowski