【问题标题】:Python Json. Getting only the last element in the json array蟒蛇Json。仅获取 json 数组中的最后一个元素
【发布时间】:2017-08-27 20:17:17
【问题描述】:

我刚开始尝试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": ""
  }
]

我想获取所有的成分ID,所以我写了这段小代码来获取成分ID

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

当我返回值时,我得到了

{
  "Ingreient ID": 19682
}

我正在尝试获取每个元素的成分 ID,但我似乎无法弄清楚。任何指针将不胜感激。谢谢

【问题讨论】:

  • 如果你能说出你期望的数据格式会很有帮助。
  • 你确定这是一个解析的python列表吗?因为没有定义变量“null”?我想你必须先解析它 json 否则你会得到一个错误

标签: python arrays json


【解决方案1】:

考虑到答案的数量,我想嘿为什么不再多一个。
如果你有复杂的表达式,你可能想看看jmespath,就像xslt for json,例如:

>>> import jmespath
>>> jmespath.search('Recipes[0].Ingredients[*].IngredientID', recipes)
[1142, 1523, 20197, 19682]

【讨论】:

    【解决方案2】:

    如果您只想要IngredientID 的列表,请使用[rec['IngredientID'] for rec in records]

    records = [{
        "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": ""
      }
    ]
    
    [rec['IngredientID'] for rec in records]
    

    输出:

    [1142, 1523, 20197, 19682]
    

    【讨论】:

      【解决方案3】:

      另一种方法,默认字典

      from collections import defaultdict
      recipe_ids = defaultdict(list)
      for records in rec:
          recipe_ids['recipe id'].append(records.get('IngredientID'))
      

      【讨论】:

        【解决方案4】:

        你是 overwriting 循环内的值。因此,最终结果将是 json 中的 last 成分 ID。请尝试将值添加到 list

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

        myList 将拥有所有成分

        你甚至可以有一个一个班轮来做到这一点:

        [r['IngredientID'] for r in rec]

        这将给出一个['1142',1523,..]的列表

        【讨论】:

          【解决方案5】:

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

          所以首先将值创建为一个空列表(在循环之前),然后在循环的每次迭代中,追加到该列表:

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

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

              value.append(rec)
          

              value.append(records['IngredientID'])
          

          【讨论】:

          • 谢谢你,我不敢相信我没有考虑到这一点,我想我想太多了,或者只是没有考虑清楚。谢谢。
          【解决方案6】:

          如果您只想要 id,可以使用列表推导式,如下所示:

          ids = [records['IngredientID'] for records in recipes['Recipes'][0]['Ingredients']]
          

          【讨论】:

            【解决方案7】:

            当前实现的一个问题是,每次找到新的ingredient ID 时,value 的值都会被覆盖。如果您需要获取值列表,则必须确保保留所有旧值,即使添加新值也是如此。

            如果您将values 设为一个列表,然后使用追加,您将获得您正在寻找的所有值:

            values = []
            for records in rec:
                ingredient_id = records.get('IngredientID', None)
                if ingredient_id:
                    values.append(ingredient_id)
            

            最好使用dict.get() 方法检索一个值,然后检查它是否存在;否则你可能会遇到异常。

            【讨论】:

              【解决方案8】:

              您每次都在重新分配变量value。因此,您将获得最后一个元素。相反,您应该尝试

              # Your code
              value = []
              for records in rec:
                  value.append(records['IngredientID']);
              
              # print value     # this will have all required IngredientID
              

              【讨论】:

                【解决方案9】:

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

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

                你也可以像这样将值定义为一个列表:

                value = []
                for records in rec:
                    value.append(records['IngredientID'])
                

                【讨论】:

                  猜你喜欢
                  • 2016-09-29
                  • 2020-06-15
                  • 2017-11-08
                  • 1970-01-01
                  • 2012-06-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2021-10-22
                  • 2014-10-17
                  相关资源
                  最近更新 更多