Home > Software design >  Load JSON in SwiftUI with arbitrary keys
Load JSON in SwiftUI with arbitrary keys

Time:10-23

I have a pretty simple JSON file I would like to load into a SwiftUI project. The JSON file looks like this:

{
  "all": ["foo", "bar", "baz", ...],
  "4": ["asd", "qwe", ...],
  "25": ["something", "another", ...],
  ...
  "2": ["xxx", "yyy", ...]
}

Pretty simple, a dictionary where each value is a list of strings. The keys are "all" and then an arbitrary number of integers such as "1", "123" and so on. They must not be in order, they can be any number, and there may be any number of them. So I don't know before hand how many keys there are.

I have managed to get this JSON into a variable of type String. But now I am stuck with how to parse this so I can for example fetch the list at key "all", or check if the key "123" exists and if so get that list.

How do I do that in SwiftUI?

Oh, and by the way, the string are Unicode and contain special characters like åäö.

CodePudding user response:

try this approach:

struct ContentView: View {
    
    @State var dataList: [String:[String]] = [:]
    
    var body: some View {
        List(Array(dataList.keys), id: \.self) { key in
            Section(header: Text(key).foregroundColor(.red).font(.headline)) {
                if let values = dataList[key] {
                    ForEach(values, id: \.self) { item in
                        Text("\(item)")
                    }
                }
            }
        }
            .onAppear {
                let json = """
{
  "all": ["foo", "bar", "baz"],
  "4": ["asd", "qwe"],
  "25": ["something", "another"],
  "2": ["xxx", "yyy", "åäö"],
  "åäö": ["qwerty", "uiop", "dfghjkh"]
}
"""
                if let data = json.data(using: .utf8) {
                    do {
                        self.dataList = try JSONDecoder().decode([String: [String]].self, from: data)
                    } catch {
                        print("decode error: \(error)")
                    }
                }
                
            }
    }
    
}
  • Related