2017-01-06 71 views
2

我正在使用json_encode将数组转换为json。但是,如果某个键的值为空,json会给出大括号{}。我希望该值应该为空或“”空白。请帮助。下面是代码:json_encode函数返回大括号{}当数组为空php

<?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":{}} 
+0

尝试在编码之前检查你的内容。 – Fyntasia

+1

您正在查看错误的地方,'simplexml_load_string'生成空对象,所以'json_encode()'正确地将它们编码为'{}':https://eval.in/710579 – jeroen

回答

2

这是因为你的$dealer是一个空数组这JSON是相同{}

使用三元

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

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

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

echo $objectJson =json_encode($data); 

,如果你只是显示它并没有在代码中再次使用下面可以避免声明它,而不是仅仅显示它

echo json_encode($data);