I'm trying to get specific data from a bigger/nested API JSON Response. But because it's highly dynamic, it fails quite often because there are some branches missing down the JSON Tree.
Is there a good way or some best practices how to get the data?
Example:
@myrecords.cvss31 = jsonresponse["result"]["CVE_Items"][0]["impact"]["baseMetricV3"]["cvssV3"]["vectorString"]
In this case, sometimes it's throwing an error, because "cvssV3" is nil. Maybe in the future also "baseMetricV3" could be nil.
So, my approach would be to create 7 if-Statements - for every attribute. "if jsonresponse["result"].present?...", next: "if jsonresponse["result"]["CVE_Items"].present?" and so on. But that doesn't seem right.
I also tried something like "..["vectorString"].presence ||= "no NVD CVSS 3.1 Score"", but because the attribute before "vectorString" is missing, this doesn't seem to work either.
I also have a lot of other attributes to extract from that API. So basically I would have to write hundrets of conditional statements.
Is there a better way if I don't want to get ALL Data from that JSON Response extracted?
CodePudding user response:
Putting it here for anyone stumbling on this issue. By using dig:
jsonresponse.dig("result", "CVE_Items", 0, "impact", "baseMetricV3", "cvssV3", "vectorString").presence || "no NVD CVSS 3.1 Score"