Home > OS >  How to parse JSON without attribute name
How to parse JSON without attribute name

Time:10-05

options: [
"6GB RAM/128GB",
"8GB RAM/128GB",
"12GB RAM/256GB"
]

This JSON I want to parse using struct.

I have coded upto this :

struct Atts: Codable {
    let options: [Options]
    
    enum CodingKeys: String, CodingKey {
        case options
    }
}

struct Options: Codable {

}

But How to access the three elements in the "options" array?

Thanks in adv.

CodePudding user response:

Replace

let options: [Options]

With

let options: [String]

And remove struct Options: Codable { Also using enum CodingKeys: String, CodingKey { is meaningless here as you don't change key name so remove it also , so all you need is

struct Atts: Codable {
   let options: [String]
}

CodePudding user response:

struct Atts: Codable {
    let options: [String]
    enum CodingKeys: String, CodingKey {
     case options
    }
 }

extension Atts {
 public init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    options = try values.decode([String]?.self, forKey: .options)!
 }
}

then you can decode and access it by using

 let decoder = JSONDecoder()
 do {
    let options = try decoder.decode([Atts].self, from: json)
    options.forEach { print($0) }
  } catch {
    print("error")
  }
  • Related