Home > Blockchain >  How can I access a single value within a JSON array | Swift
How can I access a single value within a JSON array | Swift

Time:12-17

Essentially I have the following function execute when a tableview controller loads. Using one of the JSON response values I would like to create a conditional - how can I print the pawprint value where myid == 3 :

I have attempted to access it in DispatchQueue.main.async in the same function but I am confused how to refer to it? for example I cannot do myData.pawprint - because it is a JSON array.

private func fetchJSON() {
        guard let url = URL(string: "test.com")
        else { return }
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = "mykey=\(keyValue)".data(using: .utf8)
        
        URLSession.shared.dataTask(with: request) { [self] data, _, error in
            guard let data = data else { return }
            
            do {
                
                let decoder = JSONDecoder()
                self.structure.sort { $0.thisdate > $1. thisdate }
                let res = try decoder.decode([thisStructure].self, from: data)
                let grouped = Dictionary(grouping: res, by: { $0. thisdate })
                _ = grouped.keys.sorted()
                sections = grouped.map { thisSections(date: $0.key, items: $0.value) }
                .sorted { $0.date > $1.date }
                print(sections.map(\.date))
                
                sections.map.
                let myData = try JSONDecoder().decode(thisStructure.self, from: data)
                
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                    print("TableView Loaded")
                    
                }
            }
            catch {
                print(error)
            }
        }.resume()
        
    }

struct thisSections {
    let date : String
    var items : [thisStructure]
}


struct thisStructure: Decodable {
    let myid: Int
    let pawprint: String
    let activationid: Int
    let stopid: Int
}

Example of JSON response:

[
  {
    "myid": 3,
    "pawprint": "Print Me",
    "activationid": 2,
    "stopid": 1
  }
]

CodePudding user response:

MyData.forEach {
    item in 
   if item.myid == 3{
     prin(\(item.pawprint))
   }
}

are you looking for this ?

CodePudding user response:

you could try this approach to select, then print the specific thisStructure pawprint you want:

private func fetchJSON() {
        guard let url = URL(string: "test.com")
        else { return }

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = "mykey=\(keyValue)".data(using: .utf8)

        URLSession.shared.dataTask(with: request) { [self] data, _, error in
            guard let data = data else { return }

            do {
                let decoder = JSONDecoder()
                self.structure.sort { $0.thisdate > $1. thisdate }
                let res = try decoder.decode([thisStructure].self, from: data)
                let grouped = Dictionary(grouping: res, by: { $0. thisdate })
                _ = grouped.keys.sorted()
                sections = grouped.map { thisSections(date: $0.key, items: $0.value) }
                .sorted { $0.date > $1.date }
                print(sections.map(\.date))

                // --- here res is an array of `thisStructure`
                if let selectedOne = res.first(where: {$0.myid == 3}) {
                    print(selectedOne.pawprint)
                }

                // do not try to decode this from the data
                //  let myData = try JSONDecoder().decode(thisStructure.self, from: data)

                DispatchQueue.main.async {
                    self.tableView.reloadData()
                    print("TableView Loaded")
                }
            }
            catch {
                print(error)
            }
        }.resume()

    }
  • Related