php 去除 json 对象的空值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7741415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:17:25  来源:igfitidea点击:

strip null values of json object

phpjson

提问by Sobek

All my AJAX requests are in json format which are being parsed in javascript.

我所有的 AJAX 请求都是在 javascript 中解析的 json 格式。

How can i prevent null values being displayed in an HTML page without needing to write an if-statement in javascript for each json value?

如何防止在 HTML 页面中显示空值,而无需在 javascript 中为每个 json 值编写 if 语句?

Or should i write a custom PHP function to encode an array to json instead of using json_encode() so it doesn't display 'null' ?

或者我应该编写一个自定义 PHP 函数来将数组编码为 json 而不是使用 json_encode() 以便它不显示 'null' ?

回答by masoud

In server side with PHP,

在使用 PHP 的服务器端,

You can use array_filterbefore json_encode.

array_filter之前可以使用json_encode

array_filterwithout second argument removes nullelements of entry array, example :

array_filter没有第二个参数删除条目数组的元素,例如:

$object= array(
             0 => 'foo',
             1 => false,
             2 => -1,
             3 => null,
             4 => ''
          );

$object = (object) array_filter((array) $object);
$result = json_encode($object);

The $resultcontains:

其中$result包含:

{"0":"foo","2":-1}

As you see, the nullelements are removed.

如您所见,元素被删除。

回答by Jim S.

I'm going to add to the accepted answer because that will only work if you have a 1 dimensional object or array. If there is any array or object nesting then in order to get the accepted solution to work, you must create some sort of recursive array filter. Not ideal.

我将添加到已接受的答案中,因为这仅在您拥有一维对象或数组时才有效。如果有任何数组或对象嵌套,那么为了使可接受的解决方案起作用,您必须创建某种递归数组过滤器。不理想。

The best solution my colleague and I came up with was to actually perform a regular expression on the JSON string before it was returned from the server.

我和我的同事想出的最佳解决方案是在 JSON 字符串从服务器返回之前实际对其执行正则表达式。

$json = json_encode($complexObject);
echo preg_replace('/,\s*"[^"]+":null|"[^"]+":null,?/', '', $json);

The regular expression will remove all places in the string of the form ,"key":nullincluding any whitespace between the leading comma and the start of the key. It will also match "key":null,afterwards to make sure that no null values were found at the beginning of a JSON object.

正则表达式将删除表单字符串中的所有位置,,"key":null包括前导逗号和键开头之间的任何空格。之后它也会匹配"key":null,以确保在 JSON 对象的开头没有找到空值。

This isn't an ideal solution but it's far better than creating a recursive array filter given an object could be several dimensions deep. A better solution would be if json_encodehad a flag that let you specify if you wanted null entries to remain in the output string.

这不是一个理想的解决方案,但它比创建递归数组过滤器要好得多,因为对象可能有几个维度深。更好的解决方案是,如果json_encode有一个标志让您指定是否希望空条目保留在输出字符串中。

回答by Danny Beckett

To remove onlyNULL, but keep FALSE, '', and 0:

要删除唯一NULL,但要保持FALSE''以及0

function is_not_null($var)
{
    return !is_null($var);
}

echo json_encode(array_filter((array) $object, 'is_not_null'));

回答by baiyangliu

public function __toString() {
    $obj = clone $this;
    $keys = get_object_vars($obj);
    foreach ($keys as $key => $value) {
        if (!$value) {
            unset($obj->{$key});
        }
    }
    return json_encode($obj);
}

回答by Matteo Piazza

What about using the native JSON.stringify method on the javascript side? You can set, a second parameter, a function to remove keys with a null value. If you return undefined, the property is not included in the output JSON string (check the documentation for "the replacer parameter" at https://developer.mozilla.org/en-US/docs/Using_native_JSON#The_replacer_parameter).

在 javascript 端使用原生 JSON.stringify 方法怎么样?您可以设置第二个参数,用于删除具有空值的键的函数。如果您返回 undefined,则该属性不包含在输出 JSON 字符串中(请查看https://developer.mozilla.org/en-US/docs/Using_native_JSON#The_replacer_parameter 上的“替换器参数”文档)。

function removeNulls(obj) {
    var str = JSON.stringify(obj, function(key, val) {
        if (val == null) return undefined;
        return val;
    });
    return JSON.parse(str);
}

Then you can have a "normalized" JSON object by calling:

然后你可以通过调用一个“规范化”的 JSON 对象:

var obj = removeNulls(obj);

回答by Octavian

echo json_encode(array_filter((array) $object, function($val) {
    return !empty($val);
}));