简体   繁体   中英

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...

Example of the json file

[
  {
    "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.

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. 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)?

Well, what should your application do when any of the properties are 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. For example:

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

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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