Python代码判断JSON布尔值报错TypeError的解决方案:如何正确提取符合条件的id值
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:
Simplest check (relies on Python's truthiness, concise and readable):
if event['hasEventPlayerStatistics']: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

