Best way to create an empty object in JSON with PHP?

PhpJson

Php Problem Overview


To create an empty JSON object I do usually use:

json_encode((object) null);

casting null to an object works, but is there any other preferable way and/or any problem with this solution?

Php Solutions


Solution 1 - Php

Your solution could work..

The documentation specifies that (object) null will result in an empty object, some might therefor say that your code is valid and that it's the method to use.

> PHP: Objects - Manual > >If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty.


.. but, try to keep it safe!

Though you never know when/if the above will change, so if you'd like to be 100% certain that you will always will end up with a {} in your encoded data you could use a hack such as:

json_encode (json_decode ("{}"));

Even though it's tedious and ugly I do assume/hope that json_encode/json_decode is compatible with one another and always will evaluate the following to true:

$a = <something>;

$a === json_decode (json_encode ($a)); 

json_decode ("{}") will return a stdClass per default, using the below should therefor be considered safe. Though, as mentioned, it's pretty much the same thing as doing (object) null.

json_encode (new stdClass);

Solution 2 - Php

If you use objects as dynamic dictionaries (and I guess you do), then I think you want to use an ArrayObject.

It maps into JSON dictionary even when it's empty. It is great if you need to distinguish between lists (arrays) and dictionaries (associative arrays):

$complex = array('list' => array(), 'dict' => new ArrayObject());
print json_encode($complex); // -> {"list":[],"dict":{}}

You can also manipulate it seamlessly (as you would do with an associative array), and it will keep rendering properly into a dictionary:

$complex['dict']['a'] = 123;
print json_encode($complex); // -> {"list":[],"dict":{"a":123}}

unset($complex['dict']['a']);
print json_encode($complex); // -> {"list":[],"dict":{}}

If you need this to be 100% compatible both ways, you can also wrap json_decode so that it returns ArrayObjects instead of stdClass objects (you'll need to walk the result tree and recursively replace all the objects, which is a fairly easy task).

Gotchas. Only one I've found so far: is_array(new ArrayObject()) evaluates to false. You need to find and replace is_array occurrences with is_iterable.

Solution 3 - Php

Well, json_encode() simply returns a string from a PHP array/object/etc. You can achieve the same effect much more efficiently by doing:

$json = '{}';

There's really no point in using a function to accomplish this.

UPDATE As per your comment updates, you could try:

$test = json_encode(array('some_properties'=>new stdClass));

Though I'm not sure that's any better than what you've been doing.

Solution 4 - Php

json_encode($array, JSON_FORCE_OBJECT) will do it too. see https://www.php.net/manual/en/function.json-encode.php

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpnaView Question on Stackoverflow
Solution 1 - PhpFilip Roséen - refpView Answer on Stackoverflow
Solution 2 - PhpwrygielView Answer on Stackoverflow
Solution 3 - PhprdlowreyView Answer on Stackoverflow
Solution 4 - PhpMarc Steven PlotzView Answer on Stackoverflow