python - 当 Json 键被另一个键替换时出现 for 循环错误

标签 python json

我创建了一个 for 循环来查找 Json 文件中的键,当 price 键被“price_calendar”键替换时,我遇到了一个问题。
当客户没有在他的广告中标价时出现。
我试图用 if 语句来解决这个错误,但它不起作用。
如果有人能解释为什么它不起作用。

response = requests.post(url, headers=headers, 
data=json.dumps(payload))
status = response.status_code
result = response.json()
ads = result['ads']

for ad in ads: 
  id = ad['list_id']
  print(id)
  title = ad['subject']
  print(title)
  url = ad['url']
  print(url)
  if ad['price'][0] not in ads:
    print ('No price')
  else:
    price = ad['price'][0]
    print (price,"$")
  date = ad['first_publication_date']
  print(date)

错误:

Exception has occurred: KeyError 'price'

谢谢

最佳答案

您需要检查字典中是否存在您正在查找的基于该键的值

你不应该覆盖 id() 函数中的构建

for ad in ads: 
  id = ad['list_id']
  print(id)
  title = ad['subject']
  print(title)
  url = ad['url']
  print(url)

  #if 'price' not in ad.keys() or ad['price'][0] not in ads:
  #    print ('No price')

由于问题所有者只想检查价格是否在字典键中的任务上下文而更改

  if 'price' not in ad.keys():
    print ('No price')

  else:
    price = ad['price'][0]
    print (price,"$")
  date = ad['first_publication_date']
  print(date)

关于python - 当 Json 键被另一个键替换时出现 for 循环错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55196628/

相关文章:

python - 我应该如何使用 pandas 从数据框中的列接收第一个字符串?

python - 使用特定于列的重复过滤器在 Python 中将行 append 到 CSV

python - 处理 xml 文档中缺失的元素

python - 如何绘制 4D 图的表面?

java - 从 Hibernate 反序列化 JSON

php - 告诉另一个域上的 Controller 有新数据

python - Blender 中的 Vim 与 BPY 一起工作?

javascript - 对于每个LOOP通过JSON.Stringify图像的EXIF数据

python - 更改 pandas to_json(orient ="records") 方法的 json 格式

ios - 使用 NSDictionary 创建模型对象