Hello everybody,
I am trying to parse a JSON file that has this structure:
I am using a Codable struct to read the data.
Also, I am using this code to read the json file.
I can not figure out what I am doing wrong.
Thank you for your help.
I am trying to parse a JSON file that has this structure:
Code Block { "species":[ { "name":"Aglais io", "info": { "family":"Nymphalidae", "iNatLink":"https://www.inaturalist.org/observations?place_id=any&taxon_id=207977", "WikipediaLink":"https://en.wikipedia.org/wiki/Aglais_io", "otherName":"European Peacock Butterfly" } }, { "name":"Aglais urticae", "info": { "family":"Nymphalidae", "iNatLink":"https://www.inaturalist.org/observations?place_id=any&taxon_id=54468", "WikipediaLink":"https://en.wikipedia.org/wiki/Small_tortoiseshell", "otherName":"Small Tortoiseshell" } } ] }
I am using a Codable struct to read the data.
Also, I am using this code to read the json file.
Code Block struct Species: Codable { let name: String struct info: Codable { let family: String let iNatLink: String let WikipediaLink: String let otherName: String } } func loadSpeciesInfoJSOn() { if let filePath = Bundle.main.url(forResource: "secondJSON", withExtension: "json") { do { let data = try Data(contentsOf: filePath) let decoder = JSONDecoder() let speciesList = try decoder.decode([Species].self, from: data) print(speciesList) } catch { print("Can not load JSON file.") } } }
I can not figure out what I am doing wrong.
Thank you for your help.
Your JSON text is outlined as :
The outermost structure of it is JSON object with a single entry with the key "species" and the value is a JSON array.
You need a Codable struct with an entry species. (And a little bit fix in Species.)
Use the above struct as:
Code Block { "species": [ ... ] }
The outermost structure of it is JSON object with a single entry with the key "species" and the value is a JSON array.
You need a Codable struct with an entry species. (And a little bit fix in Species.)
Code Block struct SpeciesInfo: Codable { let species: [Species] } struct Species: Codable { let name: String let info: Info //<- struct Info: Codable { //<- let family: String let iNatLink: String let WikipediaLink: String let otherName: String } }
Use the above struct as:
Code Block let decoder = JSONDecoder() let speciesInfo = try decoder.decode(SpeciesInfo.self, from: data) let speciesList = speciesInfo.species print(speciesList)