如何检查JSON数组中是否存在某个值并继续循环

3

我正在使用for循环来确定数组中是否存在特定的键。但是到目前为止,我尝试过的所有方法都无法实现我想要的目标。

我的代码如下:

for i in range(1,len(opslag)):
     info_product = 'https://examplesite.com/'+str(opslag[i])+'.json'
     info_get = session.get(info_product)
     text_info_prdt = info_get.text
     json_info_prdt =json.loads(text_info_prdt)
     if json_info_prdt['product']['metafields']['meta_title_nl'] in json_info_prdt['product']['metafields']:
        print(json_info_prdt['product']['metafields']['meta_title_nl'])
     else:
         print(json_info_prdt['product']['id'])

因此,在这种情况下,json_info_prdt ['product'] ['metafields'] ['meta_title_nl']中的值并不存在于我正在循环遍历的每个数组中。因此,有时if else语句将起作用,并且该值将被打印出来。但是有时候值json_info_prdt ['product'] ['metafields'] ['meta_title_nl']根本不存在,会给我一个KeyError

因此,我想要做的是获取返回KeyError的所有产品的ID,但我不希望循环停止,而是继续进行直到完成。所以我也不希望循环重新启动,因为那是没有意义的。

我的JSON如下:

{
   product:{
      article_code:"",
      barcode:"",
      brand_id:null,
      created_at:"2017-07-07T12:49:23+02:00",
      data01:"",
      data02:"",
      data03:"",
      delivery_date_id:null,
      has_custom_fields:true,
      has_discounts:false,
      has_matrix:false,
      hits:0,
      hs_code:null,
      id:52847777,
      image_id:130661048,
      is_visible:true,
      price_excl:0,
      price_incl:0,
      price_old_excl:0,
      price_old_incl:0,
      product_set_id:383078,
      product_type_id:null,
      search_context:"",
      shop_id:240359,
      sku:"",
      supplier_id:null,
      updated_at:"2018-07-10T10:53:15+02:00",
      variants_count:4,
      visibility:"visible",
      weight:0,
      custom_fields:[

      ],
      variants:[

      ],
      product_relations:[

      ],
      product_categories:[

      ],
      product_discounts:[

      ],
      product_type:null,
      product_filter_values:[

      ],
      product_bundles:[

      ],
      metafields:{
         meta_title_nl:"Big House",
         meta_title_en:"cxzcxzcxz",
         meta_description_nl:"This is a big house"
      },
      supplier:null,
      product_images:[

      ],
      brand:null,
      delivery_date:null,
      image:{

      },
      nl:{

      },
      en:{

      },
      tags:null
   }
}

正如您所看到的,这个值meta_title_nl在这个中是存在的,但有时它并不存在。

2个回答

2

用于捕获错误的if-else结构称为try-except。因此,您应该使用:

try:
    print(json_info_prdt['product']['metafields']['meta_title_nl'])
except:
    print(json_info_prdt['product']['id'])

不客气。顺便说一下,在字典没有嵌套的情况下,通常会使用get方法,该方法提供了定义默认值的机会,如果键丢失。但是,对于嵌套字典,您可能需要在此之前阅读https://dev59.com/dF8e5IYBdhLWcg3wYJUN。 - SpghttCd

2

如果字典中的键有时可能不存在,则应测试该键是否存在:

更改为:

if json_info_prdt['product']['metafields']['meta_title_nl'] in json_info_prdt['product']['metafields']:

to:

if 'meta_title_nl' in json_info_prdt['product']['metafields']:

1
该死,我比想象中更接近了,这个方法有效,谢谢! - Solaiman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接