Home > Software design >  For Loop with json decode data error requires 'People' to conform to 'Sequence'
For Loop with json decode data error requires 'People' to conform to 'Sequence'

Time:11-21

I am new to swift . I created simple playground and added the file with extension json into playground . I am trying to decode the result and print the ID by using for loop but , I am getting following error .. For-in loop requires 'People.Type' to conform to 'Sequence'

Here is my json file ..

    {
    "id": "1",
    "options": [{
            "id": "11",
            "options": [{
                "id": "111",
                "options": []
            }]
        },
        {
            "id": "2",
            "options": [{
                    "id": "21",
                    "options": []
                },
                {
                    "id": "22",
                    "options": [{
                        "id": "221",
                        "options": []
                    }]
                }
            ]
        }
    ]
}

Here is the code .. I tried ..

struct People: Codable {
    let id: String
    let options: [People]
}
func loadJson(filename fileName: String) -> People? {
    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
        do {
            let data = try Data(contentsOf: url)
            let decoder = JSONDecoder()
            let jsonData = try decoder.decode(People.self, from: data)

            print("// Printing the ID of the Decode Json")

            for jsondata in jsonData {

                print("ID: \(jsonData.id)")
            }
            return jsonData
        } catch {
            print("error:\(error)")
        }
    }
    return nil
}
loadJson(filename: "people1")

Here is the screenshot of the error ..

enter image description here

CodePudding user response:

Here I got to run exactly what you are asking for, however I think you should probably consider renaming your struct to something like Person as @Vadian suggested.

struct People: Codable {
    let id: String
    let options: [People]
}

func loadJson(filename fileName: String) -> People? {
    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
        do {
            let data = try Data(contentsOf: url)
            let decoder = JSONDecoder()
            let jsonData = try decoder.decode(People.self, from: data)

            printPeople(people: [jsonData])

            return jsonData
        } catch {
            print("error:\(error)")
        }
    }
    return nil
}

func printPeople(people: [People]) {
    for person in people {
        print(person.id)
        if (!person.options.isEmpty) {
            printPeople(people: person.options)
        }
    }
}

loadJson(filename: "people")

This will print:

1
11
111
2
21
22
221

  • Related