0

I am looking to access a string that is located inside of a JSON array that is located inside of another array. I am accessing the JSON API using JSONDecoder. I am receiving errors when trying the various methods that I have used in the past when using JSON arrays.

Here is the code:

var country = [Results]()

struct Rating: Codable {
    let results: [Results]
}

struct Results: Codable {
    let iso_3166_1: String
    let release_dates: [Release_Dates]
}

struct Release_Dates: Codable {
    let certification: String
}


func loadRating() {

    let id = filmId
    let apiKey = ""
    let url = URL(string: "https://api.themoviedb.org/3/movie/\(id)/release_dates?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 rates = try! JSONDecoder().decode(Rating.self, from: data)
               self.country = rates.results
                let us = self.country.filter({ $0.iso_3166_1.contains("US") })
                print(us)


        }
        }

    })

    task.resume()
}

us prints to console

[Film.DetailsView.Results(iso_3166_1: "US", release_dates: [Film.DetailsView.Release_Dates(certification: "PG-13")])]

I am trying to access the certification string.

What would be the correct method used to achieve this?

2 Answers 2

1

us is an array of Results.

To get the first certification use this:

print(us.first!.release_dates.first!. certification)

I am force unwrapping for brevity, you should properly do it with optional binding or the guard statement.

Sign up to request clarification or add additional context in comments.

Comments

1

Pretty straightforward, the result of filter is an array and certification is in the array release_dates

let us = self.country.filter({ $0.iso_3166_1.contains("US") })
for item in us {
    for releaseDate in item.release_dates {
       print(releaseDate.certification)
    }
}

Please name your struct member names lowerCamelCased by mapping the keys with CodingKeys or with the convertFromSnakeCase strategy.

If there is only one US item, use first

if let us = self.country.first({ $0.iso_3166_1.contains("US") }) {
    for releaseDate in us.release_dates {
       print(releaseDate.certification)
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.