One possible solution could involve utilizing an optional chaining operator, but the recommended approach is to leverage a tool like JSONPath for this task.
There are various libraries available, such as jsonpath or jsonpath-plus, that offer similar functionalities.
JSONPath essentially serves as XPath for JSON data structures.
For instance, consider the following JSON example:
{ "store": {
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
Here is an example of how you can extract the authors of all books in the store using a JSONPath expression:
$.store.book[*].author
You can implement this in JavaScript like so:
const o = { /*...*/ }, // the 'store' JSON object from above
res1 = jsonPath(o, "$..author").toJSONString(); // JSONPath expression for all authors
res2 = jsonPath(o, "$..author", {resultType:"PATH"}).toJSONString();