【问题标题】:Iterate though a json object and get specific data遍历一个json对象并获取特定数据
【发布时间】:2021-02-12 20:56:27
【问题描述】:

我有一个来自 API 的 json,

    "nutrient_value": [
      {
        "Calcium": [
          "29.16",
          "mg",
          "Red",
          "0.00102858984",
          "ounce"
        ]
      },
      {
        "Choline": [
          "118.97",
          "mg",
          "Red",
          "0.00419654778",
          "ounce"
        ]
      },
      {
        "Copper": [
          "0.12",
          "mg",
          "Red",
          "0.00000423288",
          "ounce"
        ]
      },
      {
        "Crude fat": [
          "29.16",
          "g",
          "Green",
          "1.02858984",
          "ounce"
        ]
      },
      {
        "Folate": [
          "11.66",
          "mcg",
          "Red",
          "0.00000041129484",
          "ounce"
        ]
      },
      {
        "Iodine": [
          "0.0",
          "mcg",
          "Red",
          "0.0",
          "ounce"
        ]
      },
      {
        "Iron": [
          "4.08",
          "mg",
          "Yellow",
          "0.00014391792",
          "ounce"
        ]
      },
      {
        "Magnesium": [
          "34.99",
          "mg",
          "Green",
          "0.00123423726",
          "ounce"
        ]
      },
      {
        "Manganese": [
          "0.02",
          "mg",
          "Red",
          "0.00000070548",
          "ounce"
        ]
      },
      {
        "Niacin (B3)": [
          "9.04",
          "mg",
          "Green",
          "0.00031887696",
          "ounce"
        ]
      },
      {
        "Omega-3 excl. ALA and SDA": [
          "0.02",
          "g",
          "Red",
          "0.00070548",
          "ounce"
        ]
      },
      {
        "Omega-6": [
          "0.02",
          "g",
          "Red",
          "0.00070548",
          "ounce"
        ]
      },
      {
        "Pantothenic acid (B5)": [
          "1.07",
          "mg",
          "Red",
          "0.00003774318",
          "ounce"
        ]
      },
      {
        "Phosphorus": [
          "332.42",
          "mg",
          "Red",
          "0.01172578308",
          "ounce"
        ]
      },
      {
        "Potassium": [
          "573.48",
          "mg",
          "Yellow",
          "0.02022893352",
          "ounce"
        ]
      },
      {
        "Protein": [
          "36.94",
          "g",
          "Green",
          "1.30302156",
          "ounce"
        ]
      },
      {
        "Riboflavin (B2)": [
          "0.29",
          "mg",
          "Red",
          "0.00001022946",
          "ounce"
        ]
      },
      {
        "Selenium": [
          "30.72",
          "mcg",
          "Red",
          "0.00000108361728",
          "ounce"
        ]
      },
      {
        "Sodium (Na)": [
          "128.3",
          "mg",
          "Green",
          "0.0045256542",
          "ounce"
        ]
      },
      {
        "Thiamin (B1)": [
          "0.08",
          "mg",
          "Red",
          "0.00000282192",
          "ounce"
        ]
      },
      {
        "Vitamin A": [
          "8.16",
          "mcg",
          "Red",
          "0.00000028783584",
          "ounce"
        ]
      },
      {
        "Vitamin C": [
          "0.0",
          "mg",
          "Green",
          "0.0",
          "ounce"
        ]
      },
      {
        "Vitamin D": [
          "0.19",
          "mcg",
          "Red",
          "0.00000000670206",
          "ounce"
        ]
      },
      {
        "Vitamin E": [
          "0.33",
          "mg",
          "Red",
          "0.00001164042",
          "ounce"
        ]
      },
      {
        "Zinc (Zn)": [
          "8.71",
          "mg",
          "Red",
          "0.00030723654",
          "ounce"
        ]
      },
      {
        "Calories": [
          "417.96",
          "cal",
          null,
          "N/A",
          "ounce"
        ]
      },
      {
        "Omega-3/6 ratio": [
          "0.65",
          "ratio",
          "Green",
          "N/A",
          "ounce"
        ]
      },
      {
        "Calcium/Phosphorus ratio": [
          "0.06",
          "ratio",
          "Red",
          "N/A",
          "ounce"
        ]
      }
    ],

从上面的json我解码成这个

var resJson = json.decode(res);
MPD.Result _mealPlan = MPD.Result.fromJson(resJson["result"]);
///

factory Result.fromJson(Map<String, dynamic> json) => Result(
    id: json["id"],
....
    nutrientValue: List<NutrientValue>.from(json["nutrient_value"].map((x) => NutrientValue.fromJson(x))),
....
  );
"nutrient_value": []

在这个 nutrition_value 数组中,对于每个项目,我需要检查给定键(例如:“钙”)是否存在,如果存在,则获取该键的索引 [0] 和 [2] 的值:

Example key "Calcium" exists and 
valueCalcium = value of index[0]
colorCalcium = value of index[2]

"nutrient_value": [
      {
        "Calcium": [
          "29.16",
          "mg",
          "Red",
          "0.00102858984",
          "ounce"
}

我怎样才能以迭代的方式做到这一点?

我试过了

_mealPlan.nutrientValue.forEach((element) {
        if(element.calcium.isNotEmpty){
          valCalcium = element.calcium[0];
          print(valCalcium);//_mealPlan.nutrientValue[0].calcium[0];
          calciumClr = element.calcium[2];
          print(calciumClr);
        }
      });

但这似乎不是正确的方法。

我在后面的代码中使用了这两个索引值。

【问题讨论】:

  • 您好,感谢您的评论。我设法通过解码将 nutrition_values 部分转换为可读格式。现在我手头有这份清单。如何在高于要求的单元中进行迭代?
  • 如果你解析了所有内容并且你有一个 ListMaps 所以处理 for (var i = 0; i &lt; list.length; i++) 循环中的每个元素
  • 不知何故它不是一个列表,我这样做是通过解码``` resJson = json.decode(res); MPD.Result _mealPlan = MPD.Result.fromJson(resJson["result"]); ```

标签: arrays json flutter dart


【解决方案1】:

你可以这样做:

void main() {
  Map<String, dynamic> data = {
    "success": true,
    "result": {
      "id": 7,
      "daily_allowance_actual_percentage": {
        "Bone": [0, "Red"],
        "Muscle Meat": [100, "Red"]
      },
      "daily_calories_from_this_meal_plan": "417.96",
      "imperial_weight_of_one_meal": "2.2857552",
      "meal_ingredients_would_make": 3,
      "meals_per_day": 3,
      "nutrient_value": [
        {
          "Calcium": ["29.16", "mg", "Red", "0.00102858984", "ounce"]
        },
        {
          "Choline": ["118.97", "mg", "Red", "0.00419654778", "ounce"]
        },
        {
          "Copper": ["0.12", "mg", "Red", "0.00000423288", "ounce"]
        },
        {
          "Crude fat": ["29.16", "g", "Green", "1.02858984", "ounce"]
        },
        {
          "Folate": ["11.66", "mcg", "Red", "0.00000041129484", "ounce"]
        },
        {
          "Iodine": ["0.0", "mcg", "Red", "0.0", "ounce"]
        },
        {
          "Iron": ["4.08", "mg", "Yellow", "0.00014391792", "ounce"]
        },
        {
          "Magnesium": ["34.99", "mg", "Green", "0.00123423726", "ounce"]
        },
        {
          "Manganese": ["0.02", "mg", "Red", "0.00000070548", "ounce"]
        },
        {
          "Niacin (B3)": ["9.04", "mg", "Green", "0.00031887696", "ounce"]
        },
        {
          "Omega-3 excl. ALA and SDA": [
            "0.02",
            "g",
            "Red",
            "0.00070548",
            "ounce"
          ]
        },
        {
          "Omega-6": ["0.02", "g", "Red", "0.00070548", "ounce"]
        },
        {
          "Pantothenic acid (B5)": [
            "1.07",
            "mg",
            "Red",
            "0.00003774318",
            "ounce"
          ]
        },
        {
          "Phosphorus": ["332.42", "mg", "Red", "0.01172578308", "ounce"]
        },
        {
          "Potassium": ["573.48", "mg", "Yellow", "0.02022893352", "ounce"]
        },
        {
          "Protein": ["36.94", "g", "Green", "1.30302156", "ounce"]
        },
        {
          "Riboflavin (B2)": ["0.29", "mg", "Red", "0.00001022946", "ounce"]
        },
        {
          "Selenium": ["30.72", "mcg", "Red", "0.00000108361728", "ounce"]
        },
        {
          "Sodium (Na)": ["128.3", "mg", "Green", "0.0045256542", "ounce"]
        },
        {
          "Thiamin (B1)": ["0.08", "mg", "Red", "0.00000282192", "ounce"]
        },
        {
          "Vitamin A": ["8.16", "mcg", "Red", "0.00000028783584", "ounce"]
        },
        {
          "Vitamin C": ["0.0", "mg", "Green", "0.0", "ounce"]
        },
        {
          "Vitamin D": ["0.19", "mcg", "Red", "0.00000000670206", "ounce"]
        },
        {
          "Vitamin E": ["0.33", "mg", "Red", "0.00001164042", "ounce"]
        },
        {
          "Zinc (Zn)": ["8.71", "mg", "Red", "0.00030723654", "ounce"]
        },
        {
          "Calories": ["417.96", "cal", null, "N/A", "ounce"]
        },
        {
          "Omega-3/6 ratio": ["0.65", "ratio", "Green", "N/A", "ounce"]
        },
        {
          "Calcium/Phosphorus ratio": ["0.06", "ratio", "Red", "N/A", "ounce"]
        }
      ],
      "pet_name": "tim",
      "show_weight_of_balanced_meal": true,
      "suggestion": {
        "add_food": {
          "Red": [
            {
              "Calcium": ["Amaranth, grain, whole, uncooked", "Apple, dried"]
            },
            {
              "Copper": ["Amaranth, grain, whole, uncooked", "Apple, dried"]
            },
            {
              "Folate": [
                "Amaranth, grain, whole, uncooked",
                "Apple, fuji, unpeeled, raw"
              ]
            },
            {
              "Iodine": ["Amaranth, grain, whole, uncooked", "Apricot, dried"]
            },
            {
              "Manganese": ["Amaranth, grain, whole, uncooked", "Apple, dried"]
            },
            {
              "Omega-3 excl. ALA and SDA": ["Bass, fillet, raw", "Beef Brain"]
            },
            {
              "Omega-6": ["Amaranth, grain, whole, uncooked", "Avocado, raw"]
            },
            {
              "Pantothenic acid (B5)": [
                "Amaranth, grain, whole, uncooked",
                "Apple, dried"
              ]
            },
            {
              "Riboflavin (B2)": [
                "Amaranth, grain, whole, uncooked",
                "Apple, fuji, unpeeled, raw"
              ]
            },
            {
              "Thiamin (B1)": [
                "Amaranth, grain, whole, uncooked",
                "Apple, fuji, unpeeled, raw"
              ]
            },
            {
              "Vitamin A": ["Bean, edamame, from frozen, cooked", "Beef Brain"]
            },
            {
              "Vitamin D": ["Beef kidney, raw", "Beef liver, raw"]
            },
            {
              "Vitamin E": ["Amaranth, grain, whole, uncooked", "Apple, dried"]
            },
            {
              "Crude fat": ["Amaranth, grain, whole, uncooked", "Apple, dried"]
            },
            {
              "Magnesium": ["Amaranth, grain, whole, uncooked", "Apple, dried"]
            },
            {
              "Niacin (B3)": [
                "Apple, fuji, unpeeled, raw",
                "Apple, golden delicious, unpeeled, raw"
              ]
            },
            {
              "Protein": ["Amaranth, grain, whole, uncooked", "Apple, dried"]
            },
            {
              "Sodium (Na)": [
                "Amaranth, grain, whole, uncooked",
                "Apple, dried"
              ]
            }
          ],
          "Yellow": []
        },
        "remove_food": {
          "Red": [
            {
              "Choline": ["Beef, mince, 15% fat, raw"]
            },
            {
              "Phosphorus": ["Beef, mince, 15% fat, raw"]
            },
            {
              "Selenium": ["Beef, mince, 15% fat, raw"]
            },
            {
              "Zinc (Zn)": ["Beef, mince, 15% fat, raw"]
            }
          ],
          "Yellow": [
            {
              "Iron": ["Beef, mince, 15% fat, raw"]
            },
            {
              "Potassium": ["Beef, mince, 15% fat, raw"]
            }
          ]
        }
      },
      "total_calories_in_a_meal_plan": 645,
      "total_imperial_weight_of_a_meal_plan": 10.5822,
      "total_weight_of_a_meal_plan": 300,
      "weight_of_one_meal": "64.8",
      "feeding_plan_details": [
        {
          "id": 23,
          "imperial_quantity": 10.5822,
          "quantity": 300,
          "food": {
            "id": 6,
            "bone_percentage": 0,
            "name": "Beef, mince, 15% fat, raw"
          }
        }
      ]
    }
  };

  List<Map<String, dynamic>> nutrientValue = data["result"]["nutrient_value"];

  List<Map<String, dynamic>> filteredData = nutrientValue
      .where((Map<String, dynamic> element) =>
          element.keys.toList()[0] == "Calcium")
      .toList();

  for (Map<String, dynamic> i in filteredData) {
    print("${i[i.keys.toList()[0]][0]} && ${i[i.keys.toList()[0]][2]}");
  }
}

【讨论】:

  • 感谢 chinky 的回复。我最终需要的是这样分配。 ``` valCalcium = _mealPlan.nutrientValue[0].calcium[0];钙Clr = _mealPlan.营养价值[0].钙[2]; valCholine = _mealPlan.nutrientValue[1].choline[0]; cholineClr = _mealPlan.nutrientValue[1].choline[2]; .....```
  • @JasonWaku 那是不可能的。无法迭代地将列表的值分配给任意变量。
  • @JasonWaku 我不明白你的意思,你能更模块化吗?
  • 我在@chinky那里更新了我的问题,你可以参考一下,希望现在可以理解了
  • @JasonWaku 问题是关于从一个 Map 中获取索引 0 和 2 的元素,该 Map 的键是来自 nut_value 列表中的“钙”,不是吗?
猜你喜欢
  • 1970-01-01
  • 2017-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多