Home > other >  How can I print the country value from my JSON file in Swift?
How can I print the country value from my JSON file in Swift?

Time:01-19

I know that this could be an easy answer, but for me is difficult. I have a Swift JSON file that loads successfully into my UserData variable. But I want to get a value from that data set. I get the error: Value of type '[UserData]' has no member 'state'

[
  {
    "state":"Alaska",
    "latitude":61.3850,
    "longitude":-152.2683,
    "stateTax":"7%"
  },
  {
    "state":"Alabama",
    "latitude":32.7990,
    "longitude":-86.8073,
    "stateTax":"13.5%"
  },
  {
    "state":"Arkansas",
    "latitude":34.9513,
    "longitude":-92.3809,
    "stateTax":"11.625%"
  }
]

My data set UserData:

[LoadFromJSON.UserData(state: "Alaska", latitude: 61.385, longitude: -152.2683, stateTax: "7%"), LoadFromJSON.UserData(state: "Alabama", latitude: 32.799, longitude: -86.8073, stateTax: "13.5%"), LoadFromJSON.UserData(state: "Arkansas", latitude: 34.9513, longitude: -92.3809, stateTax: "11.625%")]

My code and the error line:

 do {
                let data =  try Data(contentsOf: fileLocation)
                let jsonDecoder = JSONDecoder()
                let dataFromJson = try jsonDecoder.decode([UserData].self, from: data)
                
                self.userData = dataFromJson
                
                print(userData)
                print(dataFromJson.state)  // Value of type '[UserData]' has no member 'state'
                
            } catch {
                print(error)
            }

CodePudding user response:

dataFromJson is array of UserData, so you need to iterate like this.


do {
                let data =  try Data(contentsOf: fileLocation)
                let jsonDecoder = JSONDecoder()
                let dataFromJson = try jsonDecoder.decode([UserData].self, from: data)
                
                self.userData = dataFromJson
                dataFromJson.forEach{ user in

                    print(user.state)

                }
                
                print(userData)
                
                
            } catch {
                print(error)
            }

  •  Tags:  
  • Related