The problem
Handeling complex JSON structures can get tricky in bigger applications. Especially when some properties have sub properties you need, but the parent property is optional.
A quick example can illustrate this problem.
1
2
3
4
5
6
7
8
9
10
{
"name": "John Doe",
"date-of-birth": "2000-12-01",
"email": "j.doe@provider.com",
"address": {
"street": "Main",
"houseNumber": "3454",
"bus": "2b"
}
}
This might be a normal looking JSON describing a person. In the database you might, or might not have the address, it is not mandatory therefore when getting the street name, we will have to check if the address exists first.
1
2
3
4
5
6
7
const john = { /* see above */ };
const address = john.address;
let street = undefined;
if (address) {
street = address.street;
}
This is already a bit shaky implementation, you have to use a let while you know that constants are better… You have a if that looks a tad ugly… But try to imagine what would happen if we have more complex JSON structures that have complex optional properties in optional properties?
1
2
3
4
5
6
7
8
9
{
"optional1": {
"optional2": {
"optional3": {
"gold": "I know you want me!"
}
}
}
}
How would we tackle this?
1
2
3
4
5
6
7
8
9
10
11
12
13
const obj = { /* see above */ };
const optional1 = obj.optional1;
let gold = undefined;
if (optional1) {
let optional2 = optional1.optional2;
if (optional2) {
let optional3 = optional2.optional3;
if (optional3) {
gold = optional3.gold;
}
}
}
Now this looks completely silly… what would happen if you go 100 layers deep, you know, sure, that will never happen… until it does.