I have a JSON file in my app bundle that looks like this
{
"1": "cat",
"2": "dog",
"3": "elephant"
}
What I'd like is to be able to find the value for the "2" key for example ("dog").
I'm using this extension to decode the json file:
let config = Bundle.main.decode(Config.self, from: "config.json")
And I have this struct defined:
struct Config: Codable {
let id: String
let animal: String
}
But how do I find the animal name for the "2" key?
CodePudding user response:
You seem to be trying to decode your JSON as if it were an array of your Config
structs - that would look like this:
[
{
"id": "1",
"animal": "cat"
},
{
"id": "2",
"animal": "dog"
},
{
"id": "3",
"animal": "elephant"
}
]
But your data (config.json) isn't that, it's just a JSON dictionary of String keys with String values.
You can instead "decode" it as just a String: String dictionary like:
let dict = Bundle.main.decode([String: String].self, from: "config.json")
and then dict["2"]
would indeed be an optional string, with a value of .some("dog")
Or perhaps you mean your JSON to be an array of Config
's, if you change the contents of config.json file to the above, and then decode it with:
let config = Bundle.main.decode([Config].self, from: "config.json")
Then the animal with id of 2 would be, e.g.
config.first(where: { $0.id == "2" })?.animal