【问题标题】:json_encode function return Braces {} when array is empty in php当 php 中的数组为空时,json_encode 函数返回大括号 {}
【发布时间】:2017-05-21 01:01:29
【问题描述】:

我正在使用 json_encode 将数组转换为 json。但是如果某些 key 的 value 为空,json 会给出大括号 {} 。我希望该值应为 null 或 "" 空白。请帮忙。下面是代码:

<?php
$postData='<Lead>
<General>
<dealer></dealer></General> </Lead>';
 $array_data = json_encode(simplexml_load_string($postData));
$array_data=json_decode($array_data) ;
$dealer=$array_data->General->dealer;
$data=array('dealer'=>$dealer);
echo  $objectJson =json_encode($data);
?>


response is : {"dealer":{}}

【问题讨论】:

  • 在编码之前尝试检查您的内容。
  • 你看错地方了,simplexml_load_string 生成空对象,所以json_encode() 正确地将它们编码为{}eval.in/710579

标签: php json xml


【解决方案1】:

这是因为您的$dealer 是一个空数组,在json 中与{} 相同

使用三进制

'dealer'=>((!$dealer) ? $dealer : null)

这意味着如果$dealer 为空,则分配一个null,这会将您的空数组或json 中的{} 更改为null

$data=array('dealer'=>((!$dealer) ? $dealer : null));

还有

echo  $objectJson =json_encode($data);

如果您只是显示它而不在下面的代码中再次使用它,请避免声明它而不是只显示它

echo json_encode($data);

【讨论】:

    猜你喜欢
    • 2015-03-27
    • 2016-06-02
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2013-08-29
    • 2019-02-03
    相关资源
    最近更新 更多