简体   繁体   English

如何处理属性为null的json文件

[英]How can I handle with json file with null attributs

I need to read a json file and print the data on a table The json file has a lot of objects, and objects inside objects, arrays... 我需要读取一个json文件并在表上打印数据json文件中有很多对象,以及对象,数组内的对象...

Example of the json file json文件的示例

[
  {
    "id_transaction": 116,
    "company": "ABC",
    "verified": true,
    "date": "2019-04-09T13:31:20.429Z",
    "bio_data": {
      "id": "string",
      "data": "string",
      "digital": [
        {
          "name": "value1",
          "digital": ""
        },
        {
          "name": "value2",
          "digital": "value2"
        },
        {
          "name": "",
          "digital": "value3"
        }       
      ]
    },
    "info_data": {
      "value1": "value1",
      "value2": "",
      "value3": "",
      "value4": "value4",
      "value5": 1.0,
      "value6": ""      
    }
  }
]

Any data of this json file can be null, the objects bio_data and info_data can be null, the array digital can be null, and the others simple atributs ( company , date etc..) can be null. 此json文件的任何数据都可以为null,对象bio_datainfo_data可以为null, digital数组可以为null,其他简单属性( companydate等)可以为null。

What's the best way to deal with null values? 处理空值的最佳方法是什么? For now, I was dealing with each case, changing the null value to - , but that's not the most intelligent way. 现在,我正在处理每种情况,将null值更改为- ,但这不是最明智的方法。 Follow an example: 举个例子:

id_transaction !== null ? id_transaction : ' - '
info_data !== null ? info_data.value1 : ' - '
bio_data.digital[0] !== undefined ? bio_data.digital[0].name] : '-'

How can I create a fucntion to deal with it? 我该如何创建功能来应对呢? Or exists a better way to deal with it (i'm using react)? 还是存在一种更好的处理方式(我正在使用React)?

Well, what should your application do when any of the properties are null? 那么,当任何一个属性为null时,您的应用程序应该怎么做? Should it: 应该是:

  • skip that property? 跳过那个财产?
  • use a default value such as '-' ? 使用默认值,例如'-'吗?
  • throw an exception? 抛出异常?

You'll need to specify that yourself, there is no standard answer. 您需要指定自己,没有标准答案。

Once you have specified that, you can use the and- and or-operators ( && and || ) to shorten your code a bit. 指定后,就可以使用and-和or运算符( &&|| )来缩短代码。 For example: 例如:

let name = bio_data.digital && bio_data.digital[0] && bio_data.digital[0].name || 'Unknown';

See also: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM