-3

Here is the general structure of a team from our JSON file:

{"Team11":{
   "results":{
      "leg1":[
         {"g":"m","n":"Name1"}
       ],"leg2":[
         {"g":"m","n":"Name2"}
       ],"leg3":[
         {"g":"m","n":"Name3"}
       ],"leg4":[
         {"g":"m","n":"Name4"}
       ],"leg5":[
         {"g":"m","n":"Name5"}
       ],"leg6":[
         {"g":"m","n":"Name6"}
       ],"leg7":[
         {"g":"m","n":"Name7"},{"g":"m","n":"Name8"}
       ]
  },"tn":"TeamName",
  "division":"co"
} 
}

So far we are able to parse up into results categories leg1, leg2, etc. Accessing the info contained in the bracket arrays has not worked so far.

My current idea on why it is failing is because we are storing the JSON teams incorrectly via String:Any.

My other theory is I just haven't been able to find the correct documentation. Any pointers on where to look or tips would be huge!

CoolHands
  • 25
  • 7

2 Answers2

2

Make sure to add What hasn't worked for you and what you have tried? As a New contributor you need to learn how to post questions. Give it a try with my below answer.

Use Codable to parse the JSON like below,

let welcome = try? newJSONDecoder().decode(Welcome.self, from: jsonData)


// Welcome
struct Welcome: Codable {
    let team11: Team11

    enum CodingKeys: String, CodingKey {
        case team11 = "Team11"
    }
}

// Team11
struct Team11: Codable {
    let results: [String: [Result]]
    let tn, division: String
}

// Result
struct Result: Codable {
    let g, n: String
}

Note: Your JSON is missing open and ending curly brackets, and I've updated that in your question.

Harish
  • 2,496
  • 4
  • 24
  • 48
0

Are you trying to parse the JSON manually? I'm not sure where you're at with your code, but the standard way to parse a JSON string into an object is this:

let jsonData = myJSONString.data(using: .utf8)

There is an issue with your JSON though. You can validate a JSON file on this link.

  • I'll need to include code next time, my fault. I already can access the JSON file and parse through most of it, just couldn't receive certain nested elements, and the JSON above is an excerpt of the trouble area. – CoolHands Mar 10 '20 at 18:54
  • JSON should always come in Data, never in a String. – gnasher729 Mar 10 '20 at 19:41