【问题标题】:How to convert php null values to null in JSON string?如何将 php null 值转换为 JSON 字符串中的 null?
【发布时间】:2013-08-21 02:56:02
【问题描述】:

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

我正在使用 PHP POST 调用从表单接收值,然后使用这些值创建 JSON 格式的字符串。问题在于 NULL 值以及真值和假值。当这些值包含在来自 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 空值,而不是让它为空?有没有转换它们的方法?

【问题讨论】:

    标签: php json type-conversion


    【解决方案1】:

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

    【讨论】:

    • 但是如果有人想向 JSON 字符串添加额外的数据怎么办? json_encode 不是一个可行的选择。
    • @denoise 解码字符串,添加新值并编码以获得新的 JSON 字符串
    【解决方案2】:

    不要手动将 JSON 拼凑在一起!

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

    【讨论】:

    • 嗯,在某些情况下使用 json_encode 是不可行的,并且“手动”编码让您可以在提取数据的同时对其进行流式传输
    • 同意。但是,人们应该知道自己在做什么。 ;) 我仍然会使用 json_encode 以正确的语法对单个值或子对象进行编码。
    【解决方案3】:

    你可以做一些检查:

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

    【讨论】:

    • $null_value = 'null' 的问题在于,它会将值转换为字符串,而接收方不期望字符串值然后返回错误。但是 json_encode 是正确的,不知道为什么我忘记了这个方法。感谢您的全面回答。
    猜你喜欢
    • 2022-10-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    • 2012-04-12
    • 2021-09-03
    • 2021-04-04
    • 1970-01-01
    相关资源
    最近更新 更多