Home > front end >  How to Parse JSON when the object name is a number?
How to Parse JSON when the object name is a number?

Time:05-26

I have been trying to parse the JSON data I get from my browser, however, I've run into a problem. In the browser, when I copy the path of the property: bedrooms, this is the path I get:

  • 0.bedrooms

The 0 is the name of the object, and bedrooms is listed under that object as a property. When I try to create a variable with the name 0, Swift does not allow it, and without this variable, I can't match the path.

Here is my code for the different objects in the form of structs:

    struct HomeData: Codable{
        let 0: Object0 <--------This line does not work
    }

    struct Object0: Codable{
        let bathrooms: Double
        let bedrooms: Double
        let price: Int
        let rawAdress: String
        let squareFootage: Int
        let propertyType: String
    }

Here is the code to parse the JSON:

    func parseJSON(homeData: Data){
            let decoder = JSONDecoder()
            do{
                let decodedData = try decoder.decode(HomeData.self, from: homeData)
                print(decodedData.0.bathrooms) <---This line gives an error as well
            }catch{
                print(error)
            }
    }

How can I parse this data? Any help will be much appreciated!

Also, here is the data. Data

CodePudding user response:

According to your screenshot the root object is an array

struct HomeData: Decodable {
    let bathrooms: Double
    let bedrooms: Double
    let price: Int
    let rawAddress: String
    let squareFootage: Int
    let propertyType: String
}

func parseJSON(homeData: Data){
        let decoder = JSONDecoder()
        do{
            let decodedData = try decoder.decode([HomeData].self, from: homeData)
            print(decodedData.first?.bathrooms
        }catch{
            print(error)
        }
}
  • Related