使用 PHP 在 JSON 中创建空对象的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8595627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to create an empty object in JSON with PHP?
提问by pna
To create an empty JSON object I do usually use:
要创建一个空的 JSON 对象,我通常使用:
json_encode((object) null);
casting null to an object works, but is there any other preferable way and/or any problem with this solution?
将 null 转换为对象有效,但是此解决方案还有其他更可取的方法和/或任何问题吗?
回答by Filip Roséen - refp
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.
文档指定这(object) null
将导致一个空对象,因此有些人可能会说您的代码是有效的并且它是要使用的方法。
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.
如果将任何其他类型的值转换为对象,则会创建 stdClass 内置类的新实例。如果值为 NULL,则新实例将为空。
.. 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:
尽管您永远不知道上述内容何时/是否会发生变化,因此如果您想 100% 确定{}
您的编码数据中将始终以 a 结束,您可以使用以下技巧:
json_encode (json_decode ("{}"));
Even though it's tedious and ugly I do assume/hope that json_encode/json_decode is compatible with one and other and always will evalute the following to true:
尽管它既乏味又丑陋,我确实假设/希望 json_encode/json_decode 与一个和另一个兼容,并且总是将以下评估为真:
$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_decode ("{}")
将返回一个stdClass
默认值,因此使用以下应该被认为是安全的。虽然,如前所述,它与做几乎相同的事情(object) null
。
json_encode (new stdClass);
回答by wrygiel
If you use objects as dynamic dictionaries (and I guess you do), then I think you want to use an ArrayObject.
如果您使用对象作为动态字典(我猜您是这样做的),那么我认为您想使用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):
即使它是空的,它也会映射到 JSON 字典中。如果您需要区分列表(数组)和字典(关联数组),那就太好了:
$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 bothways, 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).
如果您需要这两种方式都100% 兼容,您还可以进行包装,json_decode
以便它返回ArrayObjects
而不是stdClass
对象(您需要遍历结果树并递归替换所有对象,这是一项相当简单的任务)。
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
.
陷阱。到目前为止我只找到了一个:is_array(new ArrayObject())
评估为false
. 您需要查找并替换is_array
出现的is_iterable
.
回答by rdlowrey
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_encode()
简单地从 PHP 数组/对象/等返回一个字符串。您可以通过执行以下操作更有效地实现相同的效果:
$json = '{}';
There's really no point in using a function to accomplish this.
使用函数来实现这一点真的没有意义。
UPDATEAs 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.
虽然我不确定这是否比你一直在做的更好。
回答by snow6oy
To create an empty object in JSON with PHP I used
使用我使用的 PHP 在 JSON 中创建一个空对象
$json=json_decode('{}');
$json->status=202;
$json->message='Accepted';
print_r($json);
which produced
其中产生
stdClass Object
(
[status] => 202
[message] => Accepted
)
which is necessary, because later I have to do this
这是必要的,因为以后我必须这样做
if(is_object($json))
回答by Anuga
I always do (Object)[];
, like:
我总是这样做(Object)[];
,例如:
$json = (Object)[]; // [] could also be array()
... play around with it in PHP ...
... 在 PHP 中玩转它 ...
$json = json_encode($json);
... now it's real JSON ...
...现在是真正的 JSON ...
回答by rishabh parashar
you can also use
你也可以使用
$var = ["key" => (object) array()];
json_encode($var);
回答by Marc Steven Plotz
json_encode($array, JSON_FORCE_OBJECT)
will do it too. see https://www.php.net/manual/en/function.json-encode.php
json_encode($array, JSON_FORCE_OBJECT)
也会这样做。见https://www.php.net/manual/en/function.json-encode.php