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


How to convert php null values to null in JSON string?

我有一个系统,它以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 null值正确地显示为JSON null值,而不是将其留空?有转换它们的方法吗?

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

不要手动将JSON拼凑在一起

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

您可以进行一些检查:

$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);