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

前端 未结 7 1794
情深已故
情深已故 2020-11-27 03:26

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 prefer

7条回答
  •  一个人的身影
    2020-11-27 04:15

    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.

提交回复
热议问题