Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle missing JSON data when creating objects? (Typescript)

Tags:

I am retrieving data from the Google Places API and casting it directly into objects for use elsewhere.

The problem is that sometimes the responses do not have all of the fields, so this causes my app to crash when the objects can't properly be created due to missing fields in the JSON response.

Here is an example of what I am talking about:

say the format of a response for example is this:

{ "a" : "some_str", "b" : "some_str", "c" : "some_str" }

but once in a while field "b" will be missing, so the response looks like this:

{ "a" : "some_str", "c" : "some_str" }

How can I account for this when I try to parse the JSON data into objects?

For example, here is a code that I would use to parse the data:

this.http.get(URL).subscribe(details => {
    let detailsObj = details.json();
    let myObj: SomeObject = {
        "fieldA" : detailsObj.a,
        "fieldB" : detailsObj.b,
        "fieldC" : detailsObj.c,
    }
});

If the field "b" doesn't exist on the JSON response, the value will be undefined on the "detailsObj" which causes a runtime error as it is trying to create an object with an undefined field.

How can I still create the object despite the partially undefined data? Ideally the data that is missing could be filled with a null.

Any pointers in the right direction would be greatly appreciated, thank you for your time!

like image 616
Biggytiny Avatar asked Jan 23 '18 06:01

Biggytiny


1 Answers

Use || to fill in null when b is missing:

"fieldB" : detailsObj.b || null,

or be more robust and specifically check for undefined:

"fieldB" : detailsObj.b === undefined ? null : detailsObj.b,

The first option is more concise and easier to read, but it will set the value to null if b is 0 or false or some other falsey value.

like image 124
Dem Pilafian Avatar answered Sep 23 '22 13:09

Dem Pilafian