Home > Net >  Grab data from nested JSON
Grab data from nested JSON

Time:04-02

Trying to grab the below JSON data. I can pull the everything but the foodNutrients. When running the below coded, I receive the following

Result: MealJournal.FoodNutrients(foodNutrients: nil)

{
   "fdcId":748967,
   "description":"Eggs, Grade A, Large, egg whole",
   "publicationDate":"12/16/2019",
   "foodNutrients":[
      {
         "type":"FoodNutrient",
         "nutrient":{
            "id":1091,
            "number":"305",
            "name":"Phosphorus, P",
            "rank":5600,
            "unitName":"mg"
         },

How would I go about grabbing foodNutrients?

I have the below code and I am getting the following results

Code:

struct FoodNutrients: Codable{
    let foodNutrients: [String]?
    
    enum CodingKeys: String, CodingKey{
        case foodNutrients = "foodNutrients"
    }
}

struct Food: Codable{
   
    let dataType: String
    let description: String
    let fdcId: Int
    let foodNutrients: [FoodNutrients]
  
}

class FoodApi {
    func getFood (){
        guard let url = URL(string: "https://api.nal.usda.gov/fdc/v1/food/748967?api_key=bRbzV0uKJyenEtd1GMgJJNh4BzGWtDvDZVOy8cqG") else { return }
        
        URLSession.shared.dataTask(with: url) { (data, _, _) in
            let results = try! JSONDecoder().decode(Food.self, from: data!)
            print(results)
        }
        .resume()
    }
    
}

CodePudding user response:

The food nutrients struct is wrong and needs to match the json. Use https://app.quicktype.io/ to generate the proper classes/structs

  • Related