1

I have JSON that looks like:

[
    {
        WWW: "2",
        XXX: "2",
        YYY: "3",
        ZZZ: "4"
    },
    {
        WWW: "2",
        XXX: "5",
        YYY: "6",
        ZZZ: "7"
    },
    {
        WWW: "2",
        XXX: "2",
        YYY: "2",
        ZZZ: "3"
    }
]

But I'm only interested in working with and Y and Z.

Howe can I remove the entire W and X columns either from the raw JSON or from the JSON in the form of an Array in SWIFT?

Only answers I can find such as here seem outdated. Thanks for suggestions.

user6631314
  • 1,751
  • 1
  • 13
  • 44
  • Decode the JSON with `JSONDecoder`(one of the top `swift` questions here on SO) and specify the CodingKeys you want to work with. – vadian Jul 11 '20 at 19:05

2 Answers2

2

Use:

dict["WWW"] = nil
dict["XXX"] = nil

or:

dict.removeValue(forKey: "WWW")
dict.removeValue(forKey: "XXX")

Better Approach would be using JSONEncoder and CodingKeys.

struct Model: Decodable {
    var yyy, zzz: String

    enum CodingKeys: String, CodingKey {
        case yyy = "YYY", zzz = "ZZZ"
    }
}
Frankenstein
  • 15,732
  • 4
  • 22
  • 47
2

Define your struct to match what you want, and then decode it:

struct Value: Decodable {
    enum CodingKeys: String, CodingKey {
        case y = "YYY"
        case z = "ZZZ"
    }
    var y: String
    var z: String
}

let value = try JSONDecoder().decode([Value].self, from: json)

This will exclude any keys you don't include.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610