Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

php

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?

like image 390
pna Avatar asked Dec 21 '11 20:12

pna


People also ask

Can a JSON object be empty?

JSON data has the concept of null and empty arrays and objects. This section explains how each of these concepts is mapped to the data object concepts of null and unset.

How do you empty an object in PHP?

An object is an instance of a class. Using the PHP unset() function, we can delete an object. So with the PHP unset() function, putting the object that we want to delete as the parameter to this function, we can delete this object.

How do you create an empty JSON array?

// create an empty array var array = []; // create an object with properties "id", "action" with mock values var object = { id: "1", action: "shout" } // add object to array array. push(object); // create encode json string var myJSONString = JSON. stringify(array);

How check JSON object is empty or not in PHP?

$x = (array)$obj; if (empty($x)) ... Or cast to an array and count() : if (count((array)$obj)) ...


1 Answers

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));  

Recommended method

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); 
like image 157
Filip Roséen - refp Avatar answered Oct 14 '22 20:10

Filip Roséen - refp