I need to retrieve data deep within a nested JSON but I've had alot of trouble doing so. The file in question can be found at https://waterservices.usgs.gov/nwis/iv/?format=json&indent=on&sites=08155200¶meterCd=00065&siteStatus=all.
// MARK: - Post
struct Post: Codable {
let name, declaredType, scope: String?
let value: PostValue?
let postNil, globalScope, typeSubstituted: Bool?
enum CodingKeys: String, CodingKey {
case name, declaredType, scope, value
case postNil
case globalScope, typeSubstituted
}
}
// MARK: - PostValue
struct PostValue: Codable {
let queryInfo: QueryInfo?
let timeSeries: [TimeSery]?
}
// MARK: - QueryInfo
struct QueryInfo: Codable {
let queryURL: String?
let criteria: Criteria?
let note: [Note]?
}
// MARK: - Criteria
struct Criteria: Codable {
let locationParam, variableParam: String?
let parameter: [JSONAny]?
}
// MARK: - Note
struct Note: Codable {
let value, title: String?
}
// MARK: - TimeSery
struct TimeSery: Codable {
let sourceInfo: SourceInfo?
// let variable: Variable?
// let values: [TimeSeryValue]?
let name: String?
}
// MARK: - SourceInfo
struct SourceInfo: Codable {
let siteName: String?
// let siteCode: [SiteCode]?
// let timeZoneInfo: TimeZoneInfo?
let geoLocation: GeoLocation?
let note, siteType: [JSONAny]?
// let siteProperty: [SiteProperty]?
}
// MARK: - GeoLocation
struct GeoLocation: Codable {
let geogLocation: GeogLocation?
let localSiteXY: [JSONAny]?
}
// MARK: - GeogLocation
struct GeogLocation: Codable {
let srs: String?
let latitude, longitude: Double?
}
The code to retrieve the data:
URLSession.shared.dataTask(with: url) { data, _, _ in
if let data = data {
let posts = try! JSONDecoder().decode(Post.self, from: data)
if let coord = (posts.value?.timeSeries?.sourceInfo?.geoLocation?.geogLocation?.srs) {
print(coord)
}
}
}.resume()
Unfortunately, this returns with the error
error: ParseJSON.playground:330:89: error: type of expression is ambiguous without more context