# 示例代码:判断 JSON 中是否存在某个 key
import json
def check_key_exists(json_data, key):
"""
检查给定的 JSON 数据中是否包含指定的 key。
参数:
json_data (dict): JSON 数据,通常是一个字典。
key (str): 要检查的 key 名称。
返回:
bool: 如果 key 存在返回 True,否则返回 False。
"""
if isinstance(json_data, dict):
return key in json_data
else:
return False
# 示例 JSON 数据
json_string = '{"name": "Alice", "age": 25, "city": "New York"}'
json_data = json.loads(json_string)
# 检查 key 是否存在
key_to_check = "age"
if check_key_exists(json_data, key_to_check):
print(f"Key '{key_to_check}' 存在于 JSON 数据中。")
else:
print(f"Key '{key_to_check}' 不存在于 JSON 数据中。")
json
模块来处理 JSON 数据。check_key_exists
函数用于检查 JSON 数据(字典)中是否存在指定的 key。上一篇:idea 运行python
下一篇:python遍历字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站