How to write JSON as Swift Struct?

No, that wouldn’t work. action and trigger are already accounted for as keys in the outer object so you can’t then use also them as keys in the inner object.

You would either need to do this:

struct Obj: Codable {
    let action: [String: String]
    let trigger: [String: String]
}

or this:

typealias Obj = [String:[String:String]]

in order for this to work using the JSON you provided:

let json = """
[
    {
        "action": {
            "type": "block"
        },
        "trigger": {
            "url-filter": "apple.com"
        }
    }
]
""".data(using: .utf8)!

let decoder = JSONDecoder()
do {
    let obj = try decoder.decode([Obj].self, from: json)
    print(obj)
}
catch {
    print(error)
}

//1st way returns an array containing struct with
//  action property: ["type": "block"] and trigger property: ["url-filter": "apple.com"]
//2nd one returns: [["action": ["type": "block"], "trigger": ["url-filter": "apple.com"]]]

(PS: Post your code as text rather than screenshots. That makes it far easier for people to help you because they can just copy/paste rather than having to retype everything in order to test it out.]

1 Like