JSharpp
JSharpp

Reputation: 559

Using JSON Arrays in swift

I am having problems accessing information that is stored inside of a JSON API whenever it is located inside of [] brackets rather than {} brackets. I am trying to search through the array and find the {} set that matches "job": "director". Problem is if I'm not using an IndexPath view such as a CollectionView I cannot access information located inside of the [] brackets.

JSON:

"crew": [
{
  "credit_id": "57ea3a02c3a3687edc00080a",
  "department": "Directing",
  "gender": 2,
  "id": 51329,
  "job": "Director",
  "name": "Bradley Cooper",
  "profile_path": "/z5LUl9bljJnah3S5rtN7rScrmI8.jpg"
},
{
  "credit_id": "57ea3a14c3a3687ff9007bd7",
  "department": "Writing",
  "gender": 2,
  "id": 51329,
  "job": "Screenplay",
  "name": "Bradley Cooper",
  "profile_path": "/z5LUl9bljJnah3S5rtN7rScrmI8.jpg"
},
{
  "credit_id": "57ea3a27925141108f008807",
  "department": "Writing",
  "gender": 2,
  "id": 224385,
  "job": "Screenplay",
  "name": "Will Fetters",
  "profile_path": null
}
],

Here is part of my code:

struct Cast: Codable {
    let character: String
    let name: String
    let profile_path: String?
}

struct Crew: Codable {
    let name: String
    let profile_path: String?
    let job: String
}

func loadCredits() {

    let id = filmId
    let apiKey = ""
    let url = URL(string: "https://api.themoviedb.org/3/movie/\(id)/credits?api_key=\(apiKey)")
    let request = URLRequest(
        url: url! as URL,
        cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData,
        timeoutInterval: 10 )

    let session = URLSession (
        configuration: URLSessionConfiguration.default,
        delegate: nil,
        delegateQueue: OperationQueue.main
    )

    let task = session.dataTask(with: request, completionHandler: { (dataOrNil, response, error) in
        if let data = dataOrNil {
            do { let credit = try! JSONDecoder().decode(Credits.self, from: data)
                self.filmCast = credit.cast
                self.filmCrew = credit.crew


                self.castCollection.reloadData()

            }
        }

        self.castCollection.reloadData()

    })

    task.resume()
}

I can use this to access the information through an indexpath as such:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = castCollection.dequeueReusableCell(withReuseIdentifier: "castCell", for: indexPath) as! CastCell

        let credit = filmCast[indexPath.row]
        let name = credit.name

        cell.castName.text = name


        return cell


}

But I am having trouble searching through the data without it being located in an IndexPath view such as UICollectionView.

So if I want to search for the job that is Director outside of the collectionview I am trying:

if filmCrew.job == "Director" {
 perform action here
  }

I am receiving the error:

Value of type '[DetailsView.Crew]' has no member 'job'

So the question I have is how to properly search through a JSON array to find the matching {} of data based on the matching value. Sorry if the question sounds dumb or confusing, I've just had problems with this since using dictionaries and arrays. It always works fine when I index it in table and collection views but I can't seem to figure out how to sift through the array.

Upvotes: 1

Views: 44

Answers (1)

Craig Siemens
Craig Siemens

Reputation: 13266

Your condition needs to go through the whole filmCrew array and find the first user that that has the job "Director", luckily there's a method that does it.

if let director = filmCrew.first(where: { $0.job == "Director" }) {
    //perform action here
}

Upvotes: 3

Related Questions