Home > database >  (Swift) Unable to decode JSON starting with { "something" : [ {
(Swift) Unable to decode JSON starting with { "something" : [ {

Time:12-31

Below is a sample of the JSON I am trying to decode:

{
  "results": [
    {
      "Modified": "2022-12-30T22:27:00",
      "Published": "2022-12-23T15:15:00",
      "access": {},
      "assigner": "[email protected]",
      "cvss": null,
      "cwe": "CWE-77",
      "id": "CVE-2022-46642",
      "impact": {},
      "last-modified": "2022-12-30T22:27:00",
      "references": [
        "https://github.com/CyberUnicornIoT/IoTvuln/blob/main/d-link/dir-846/D-Link dir-846 SetAutoUpgradeInfo command injection vulnerability.md",
        "https://www.dlink.com/en/security-bulletin/"
      ],
      "summary": "D-Link DIR-846 A1_FW100A43 was discovered to contain a command injection vulnerability via the auto_upgrade_hour parameter in the SetAutoUpgradeInfo function.",
      "vulnerable_configuration": [
        "cpe:2.3:o:dlink:dir-846_firmware:100a43:*:*:*:*:*:*:*",
        "cpe:2.3:h:dlink:dir-846:a1:*:*:*:*:*:*:*"
      ],
      "vulnerable_configuration_cpe_2_2": [],
      "vulnerable_product": [
        "cpe:2.3:o:dlink:dir-846_firmware:100a43:*:*:*:*:*:*:*"
      ]
    },

(the JSON file continues with the next { "Modified"...)

I searched for a solution and my code is as follows:

The struct

struct CVE : Decodable
{
    var id : String
    var cvss : String? = nil
    var Modified : String
    var summary : String
    
}
struct CVEdata : Decodable
{
    var results : [CVE]
}

and the JSON decoding function

    func jsonDataRequest () async
    {
        if let url = URL(string: "https://cve.circl.lu/api/query?time_start=30-12-2022,time_end=31-12-2022")
        {
             do
             {
                 let (data, _) = try await URLSession.shared.data(from: url)
                 arrCVE = try JSONDecoder().decode([CVEdata].self, from: data)
             }
             catch
            {
                 print(error)
            }
         }
    }
}

If the above algorithm is correct, how can I access the data in the arrCVE variable? I have tried a for loop for dictionary, but I think the issue is somewhere in the decoding line. Thank you

CodePudding user response:

The problem here is that the top-level container of your JSON is not an array, so for start your decoding type should be CVEData.self (instead of [CVEData].self).

Then you can access the list of CVE objects via arrCVE.results.

Don't forget that arrCVE must be redeclared accordingly:

var arrCVE: CVEdata?

  • Related