如何用Python通过键名或ID从JSON数据中获取指定值
Python通过键名或ID提取JSON中的目标值
首先注意:你提供的JSON数据不符合Python字典的语法规范,所有键名必须用双引号包裹,修正后的代码如下:
json_data = { "product": { "attributes": [ { "key": {"name": "İşlemci Tipi", "id": 168}, "value": {"name": "Apple M1", "id": 243383}, "starred": True, "description": "", "mediaUrls": [] }, { "key": {"name": "SSD Kapasitesi", "id": 249}, "value": {"name": "256 GB", "id": 3376}, "starred": True, "description": "", "mediaUrls": [] } ] } }
方法一:通过键名「İşlemci Tipi」提取
遍历attributes列表,匹配对应键名后取出值:
for attribute in json_data["product"]["attributes"]: if attribute["key"]["name"] == "İşlemci Tipi": target_value = attribute["value"]["name"] print(target_value) # 输出:Apple M1 break # 找到目标后退出循环,提升效率
方法二:通过ID值「168」提取
同样遍历列表,匹配ID后取值:
for attribute in json_data["product"]["attributes"]: if attribute["key"]["id"] == 168: target_value = attribute["value"]["name"] print(target_value) # 输出:Apple M1 break
封装成函数(复用更方便)
如果需要多次提取不同属性,可以把逻辑封装成函数:
def get_attr_value(data, target_name=None, target_id=None): for attr in data["product"]["attributes"]: if target_name and attr["key"]["name"] == target_name: return attr["value"]["name"] if target_id and attr["key"]["id"] == target_id: return attr["value"]["name"] return None # 未找到时返回None # 调用示例 print(get_attr_value(json_data, target_name="İşlemci Tipi")) # Apple M1 print(get_attr_value(json_data, target_id=168)) # Apple M1
内容的提问来源于stack exchange,提问作者piseynir
相关产品推荐
相关产品推荐

