You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码判断JSON布尔值报错TypeError的解决方案:如何正确提取符合条件的id值

Fixing the TypeError: bool is not iterable in Your JSON Parsing Code

Hey there, let's break down what's going wrong and fix it quickly!

The Root Cause

Your error TypeError: argument of type 'bool' is not iterable happens because the hasEventPlayerStatistics field in your JSON response is a boolean value (either true/false in JSON, which translates to True/False in Python after parsing with .json()).

Your original code tried to check if 'true' in event['hasEventPlayerStatistics']—this only works if the value is a string. Since it's a boolean, you can't iterate over it to look for a string substring, hence the error.

The Fix

Instead of checking for the string 'true', directly check if the boolean value is True. You have two clean options:

  1. Simplest check (relies on Python's truthiness, concise and readable):

    if event['hasEventPlayerStatistics']:
    
  2. Explicit check (great for clarity if you want to leave no room for ambiguity):

    if event['hasEventPlayerStatistics'] is True:
    

Modified Full Code

Here's your updated code with the fix, plus a small cleanup (you don't need f.close() when using with—the with block automatically handles closing the file, so that line was redundant and would actually cause an error):

import requests
headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}
with open("Live.csv", "w+", newline="", encoding="UTF-8") as f:
    titlemenu = "id" + "\n"
    f.write(titlemenu)
    url = f'https://etcetcetc.com'
    response = requests.get(url, headers=headers).json()
    events = response['events']
    for event in events:
        # Fixed the if condition here
        if event['hasEventPlayerStatistics']:
            id = event['id']
            row = str(id) + "\n"
            f.write(row)

Bonus Safety Tip

If there's a chance that hasEventPlayerStatistics might be missing from some event objects, you can add a safety check to avoid KeyError crashes:

if event.get('hasEventPlayerStatistics', False):

This uses dict.get() to return False if the key doesn't exist, keeping your code robust.

内容的提问来源于stack exchange,提问作者Digital Farmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 02:27:34