Decoding dynamic json

Hey there, I'm trying to decode an json with an dynamic dict as value.

eg.

"results": [
    {
        "id": 1799,
        "created_at": "2024-05-09T14:21:13.289655Z",
        "updated_at": "2024-05-10T11:54:25.484537Z",
        "email": "test@test.testh",
        "name": "Test",
        "attributes": {
            "name": {
                "firstname": "max",
                "lastname": "mustermann"
            },
            "anboolen": false,
            "anNumber": 1,
            "anString": "Test"
        }
    }
]

The dictionary "attributes" is always an dictionary but the content inside could be everything.

for the container of results I already created an struct and using JSONDecoder to decode, but now I have the issue with the attributes part.

Can anyone help me with this issue?

Thanks in advance!

Answered by Claude31 in 787451022

The dictionary "attributes" is always an dictionary but the content inside could be everything.

Be more explicit. Is it [String: Any] ?

Please show how you have defined the struct that will hold the decoded JSON.

How is attributes defined there ?

You may find interesting info here: https://stackoverflow.com/questions/44603248/how-to-decode-a-property-with-type-of-json-dictionary-in-swift-45-decodable-pr

Accepted Answer

The dictionary "attributes" is always an dictionary but the content inside could be everything.

Be more explicit. Is it [String: Any] ?

Please show how you have defined the struct that will hold the decoded JSON.

How is attributes defined there ?

You may find interesting info here: https://stackoverflow.com/questions/44603248/how-to-decode-a-property-with-type-of-json-dictionary-in-swift-45-decodable-pr

You can use QuickType.io to get a set of structs for your data. I just used it and got:

//   let results = try? JSONDecoder().decode(Results.self, from: jsonData)

import Foundation

// MARK: - Results
struct Results: Codable {
    let results: [Result]
}

// MARK: - Result
struct Result: Codable {
    let id: Int
    let createdAt, updatedAt, email, name: String
    let attributes: Attributes

    enum CodingKeys: String, CodingKey {
        case id
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case email, name, attributes
    }
}

// MARK: - Attributes
struct Attributes: Codable {
    let name: Name
    let anboolen: Bool
    let anNumber: Int
    let anString: String
}

// MARK: - Name
struct Name: Codable {
    let firstname, lastname: String
}

You should set the items within attributes to be optional, so it will work however many of the fields are present.

Decoding dynamic json
 
 
Q