50

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?

Michael Berkowski
271k47 gold badges452 silver badges395 bronze badges
asked Jul 26, 2012 at 13:39
1
  • This is not possible using the built-in json_encode function Commented Jul 26, 2012 at 13:40

3 Answers 3

88

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":[]}
answered Jul 26, 2012 at 13:41
Sign up to request clarification or add additional context in comments.

Comments

5

Same answer, for PHP5.4+.

$foo = [
 "bar1" => (object)["",""],
 "bar2" => ["",""]
];
echo json_encode($foo);
// {"bar1":{}, "bar2":[]}

Another simple examples, with something important to notice:

$icons = (object)["rain"=>["πŸ’§"], "sun"=>["🌞"], "lightrain"=>["🌦"]];
echo $icons->sun;
// 🌞
$icons = (object)["rain"=>"πŸ’§", "sun"=>"🌞", "lightrain"=>"🌦"];
echo $icons->sun;
// 🌞
answered Sep 14, 2018 at 18:22

Comments

-6

There answer is no. There is no way for the function to guess your intent as to which array should be array and which should be objects. You should simply cast the arrays you want as object before json_encoding them

answered Jul 26, 2012 at 13:42

1 Comment

@DarkoRomanov By casting he means "bar1" => (object)array(). The (object) casts (transform as in a smith's furnace) the array into a standard object.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.