Super newbie here.
I have this sample json named items_tmp.json
that is embedded in my project
[
{
"id": "1",
"name": "hello",
"description": "aaa"
},
{
"id": "2",
"name": "world",
"description": "bbb"
}
]
I am trying to read file, make it into a dictionary object so i could itterate through the data and call elements by key name.
So far I have this within viewDidLoad:
let itemsListJson:String = "jsons/items_tmp"
guard let urlItems = Bundle.main.url(forResource: itemsListJson, withExtension: "json") else { return }
do{
let dataItems = try Data(contentsOf: urlItems)
let jsonItems = try JSONSerialization.jsonObject(with: dataItems, options: .mutableContainers)
guard let arrayItems = jsonItems as? [Any] else {return}
print(arrayItems.count)
for i in 0 ..< arrayItems.count {
let max_damage = arrayItems[i]
print(max_damage)
}
}
catch{
print(error)
}
resulting with the following output:
2
{
description = aaa;
id = 1;
name = hello;
}
{
description = bbb;
id = 2;
name = world;
}
So I get my info but it is nor in key-->value formation
When I try getting a specific value by key like so
let name = arrayItems[i].name
I get: type any has no member name
on the other hand if I change the following line to dictionary structure:
guard let arrayItems = jsonItems as? [String: Any] else {return}
I get no data.
Not sure how its done.
Any help will be greatly appreciated