Python Json。只获取json数组中的最后一个元素

2024-10-03 00:28:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始尝试python,现在我有点左右为难。在

我试图从一个json文档打印,而我只得到数组中的最后一个元素。在

[{
    "FullMeasure": "1/2 cup", 
    "FullWeight": "", 
    "IngredientGridHeaders": null, 
    "IngredientID": 1142, 
    "IngredientName": "frozen corn", 
    "IngredientStep": 10, 
    "LanguageId": 0, 
    "PostPreparation": ", thawed, drained", 
    "PrePreparation": "", 
    "QuantityNum": 0, 
    "QuantityText": "1/2", 
    "QuantityUnit": "cup", 
    "RecipeIngredientID": 6291555, 
    "TrialMeasure": "", 
    "TrialWeight": ""
  }, 
  {
    "FullMeasure": "1/4 cup", 
    "FullWeight": "", 
    "IngredientGridHeaders": null, 
    "IngredientID": 1523, 
    "IngredientName": "red pepper", 
    "IngredientStep": 20, 
    "LanguageId": 0, 
    "PostPreparation": "s", 
    "PrePreparation": "chopped", 
    "QuantityNum": 0, 
    "QuantityText": "1/4", 
    "QuantityUnit": "cup", 
    "RecipeIngredientID": 6291554, 
    "TrialMeasure": "", 
    "TrialWeight": ""
  }, 
  {
    "FullMeasure": "2 Tbsp.", 
    "FullWeight": "", 
    "IngredientGridHeaders": null, 
    "IngredientID": 20197, 
    "IngredientName": "chopped green chiles", 
    "IngredientStep": 30, 
    "LanguageId": 0, 
    "PostPreparation": ", drained", 
    "PrePreparation": "canned ", 
    "QuantityNum": 2, 
    "QuantityText": "2", 
    "QuantityUnit": "Tbsp.", 
    "RecipeIngredientID": 6291552, 
    "TrialMeasure": "", 
    "TrialWeight": ""
  },
{
    "FullMeasure": "", 
    "FullWeight": "", 
    "IngredientGridHeaders": null, 
    "IngredientID": 19682, 
    "IngredientName": "KRAFT DELI DELUXE Process American Cheese Slice", 
    "IngredientStep": 80, 
    "LanguageId": 0, 
    "PostPreparation": "s", 
    "PrePreparation": "", 
    "QuantityNum": 4, 
    "QuantityText": "4", 
    "QuantityUnit": "", 
    "RecipeIngredientID": 6291558, 
    "TrialMeasure": "", 
    "TrialWeight": ""
  }
]

我想得到所有的ingredientID,所以我写了一段代码来获取ingredientID

^{pr2}$

当我返回值时,我得到

{
  "Ingreient ID": 19682
}

我试图得到每种元素的成分ID,但我似乎搞不清楚。如有任何建议,我们将不胜感激。谢谢你


Tags: nullcupingredientnameingredientidquantityunitlanguageidprepreparationpostpreparation
3条回答

每次通过该循环时都要替换该值。相反,你应该增加价值。在

因此,首先将值创建为空列表(在循环之前),然后在循环的每次迭代中,附加到该列表:

value = []
rec = recipes['Recipes'][0]['Ingredients']
for records in rec:
    value.append({'Ingredient ID': records['IngredientID']})

然而,拥有一个字典列表,其中每个字典都有一个具有相同已知键的值,这似乎有点毫无意义。根据您的要求,您可能需要执行以下任一操作:

^{pr2}$

或者

    value.append(records['IngredientID'])

您现在要做的是重新定义value每个循环。您需要在循环之前定义value,并将其分配给一个可以添加到其中的空列表。在

value = {'Ingredient ID':[]}
for records in rec:
    value['Ingredient ID'].append(records['IngredientID'])

也可以将值定义为如下列表:

^{pr2}$

每次都要重新分配变量value。所以你得到了最后一个元素。你应该试试

# Your code
value = []
for records in rec:
    value.append(records['IngredientID']);

# print value     # this will have all required IngredientID

相关问题 更多 >