如何通过指定id从JSON数组对象中获取label字段值
解决JSON数组中根据id获取对应label的问题
首先,你的JSON文件存在语法错误:interface数组里的两个对象之间缺少逗号,修正后的JSON如下:
{ "interface":[ {"id": "testkey", "label": "The interface block local worked!"}, {"id": "testkey2", "label": "The interface block local worked, AGAIN!"} ], "settings":[], "popup_success":[], "popup_error":[], "popup_warning":[], "other_strings":[] }
你当前代码的问题在于:parsed_dict["interface"]是数组(列表)类型,不是字典,所以不能直接用["testkey"]访问元素。要根据id获取对应的label,可以用以下两种方法:
方法1:遍历数组查找
适合单次查找或数据量不大的场景:
with open("local_en.json") as json_file: parsed_dict = json.load(json_file) target_id = "testkey" # 遍历interface数组匹配id for item in parsed_dict["interface"]: if item["id"] == target_id: print(item["label"]) break else: print(f"未找到id为{target_id}的条目")
方法2:转换为id映射字典(高效复用)
如果需要多次根据id查找,先把数组转成以id为键的字典,后续可直接通过key取值:
with open("local_en.json") as json_file: parsed_dict = json.load(json_file) # 将interface数组转为{id: label}格式的字典 interface_map = {item["id"]: item["label"] for item in parsed_dict["interface"]} # 获取指定id的label,不存在则返回提示 target_id = "testkey" print(interface_map.get(target_id, f"未找到id为{target_id}的条目"))
内容的提问来源于stack exchange,提问作者Sidney
相关产品推荐
相关产品推荐

