如何在JSON字符串中将php null值转换为null?

时间:2013-08-19 10:31:26

标签: php json type-conversion

我有一个系统以JSON字符串的形式发送和接收所有数据,因此必须将我需要发送给它的所有数据格式化为JSON字符串。

我使用PHP POST调用从表单接收值,然后使用这些值以JSON格式创建字符串。问题在于NULL值以及true和false值。当这些值包含在POST值的字符串中时,它只是将其留空,但JSON将NULL值格式化为文本null。

请参阅以下示例:

<?php

$null_value = null;
$json_string = '{"uid":0123465,"name":"John Smith","nullValue":'.$null_value.'}';
echo $json_string;

//output
{"uid":0123465,"name":"John Smith","nullValue":} 

?>

但是,我需要的正确输出是:     

$json_string = '{"uid":0123465,"name":"John Smith","nullValue":null}';
echo $json_string;

//output
{"uid":0123465,"name":"John Smith","nullValue":null} 

?>

我的问题是,如何让PHP空值正确显示为JSON空值,而不是将其留空?有转换它们的方法吗?

3 个答案:

答案 0 :(得分:2)

不要手动创建JSON字符串。 PHP具有出色的功能http://php.net/manual/en/function.json-encode.php

答案 1 :(得分:0)

不要手动拼凑JSON!

$data = array('uid' => '0123465', 'name' => 'John Smith', 'nullValue' => null);
$json = json_encode($data);

答案 2 :(得分:0)

你可以做一些检查:

$null_value = null;
if(strlen($null_value) < 1)
    $null_value = 'null';//quote 'null' so php deal with this var as a string NOT as null value
$json_string = '{"uid":0123465,"name":"John Smith","nullValue":'.$null_value.'}';
echo $json_string;

或者您可以在开头引用值null

$null_value = 'null';
$json_string = '{"uid":0123465,"name":"John Smith","nullValue":'.$null_value.'}';
echo $json_string;

但是首选的方法是在数组中收集值然后对其进行编码:

$null_value = null;
$json_string = array("uid"=>0123465,"name"=>"John Smith","nullValue"=>$null_value);
echo json_encode($json_string,JSON_FORCE_OBJECT);