null / empty json如何检查它而不是输出? [英] null / empty json how to check for it and not output?

查看:171
本文介绍了null / empty json如何检查它而不是输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json编码的数据集,我通过ajax检索。我正在尝试检索的一些数据点将返回null或为空。

I've got a json encoded dataset that I retrieve via ajax. Some of the data points I'm trying to retrieve will come back us null or empty.

但是,我不希望将null或empty显示给最终用户,或传递给其他函数。

However, I don't want those null or empty to be displayed to the end user, or passed on to other functions.

我现在正在做的是检查


    if(this.cityState!='null'){
            // do some stuff here
}

然而,对于每一行我发现自己经历了多个if语句,看起来非常低效。有没有更好的方法呢?

However, for each line I find myself going through multiple if statements, and it seems very inefficient. Is there a better way to do this?

推荐答案

由于JSON只是一种数据格式,真的无法知道哪个除非您明确检查它们,否则您的数据成员将为null。您可以随时重构代码,使其更紧凑,更易于阅读,但如果您事先不知道哪些项将为空,哪些将包含数据,则必须明确检查每个项目。

Since JSON is simply a data format, there really is no way to know which of your data members will be null unless you explicitly check them. You can always refactor your code to make it more compact and easier to read, but you will have to check each item explicitly if you do not know beforehand which will be null and which will contain data.

虽然我不知道你的代码应该做什么,但这里有一个如何重构它以使其更紧凑的例子:

While I don't know what your code is supposed to do, here is an example of how you might refactor it to make it more compact:

var data = { Name: "John Doe", Age: 25, Address: null, CityState: "Denver, CO" };
for (member in data) {
    if (data[member] != null)
        // Do work here
}

这篇关于null / empty json如何检查它而不是输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆