Python脚本解析JSON动作值不符合预期,求排查修正
问题排查与修正方案
问题场景
给定JSON的actions片段:
'actions': [ {'action_type': 'onsite_conversion.post_save', 'value': '1'}, {'action_type': 'link_click', 'value': '2'}, {'action_type': 'post', 'value': '3'}, {'action_type': 'post_reaction', 'value': '4'}, {'action_type': 'video_view', 'value': '5'}, {'action_type': 'post_engagement', 'value': '6'}, {'action_type': 'page_engagement', 'value': '7'} ],
需要按指定顺序的action_types解析对应值,不存在则填0:
action_types = ["onsite_conversion.post_save", "link_click", "post", "post_reaction", "comment", "video_view", "post_engagement", "page_engagement"]
原脚本返回结果[1, 2, 1, 3, 4, 6, 4, 0, 5, 6, 7],与预期[1,2,3,4,0,5,6,7]不符。
问题原因
- 错误的包含判断+重复遍历:原脚本在确认目标
action_type存在后,又遍历了所有actions元素,且用action in item["action_type"]做包含匹配(比如"post"会误匹配"post_reaction"、"post_engagement"),导致单次循环添加多个值,结果长度超出预期。 - 冗余操作多:每次判断
action是否存在时,都重新生成action_type列表,且重复遍历actions,效率低下。
修正方案
先将actions转换为键值对字典,通过字典直接查找对应值,避免重复遍历和错误匹配:
def get_action_values(insight): action_types = ["onsite_conversion.post_save", "link_click", "post", "post_reaction", "comment", "video_view", "post_engagement", "page_engagement"] # 把actions转成字典,key为action_type,value为对应值(无value则设为"Null") action_map = {} for item in insight.get("actions", []): action_type = item.get("action_type") if action_type: action_map[action_type] = item.get("value", "Null") action_type_values = [] for action in action_types: # 存在则取对应值,不存在填0 action_type_values.append(action_map.get(action, 0)) return action_type_values
代码说明
- 仅遍历一次
actions生成字典映射,后续查找只需O(1)时间,效率大幅提升。 - 使用
item.get("key", 默认值)避免键不存在的报错,同时处理无value的边界情况。 - 遍历指定
action_types时直接从字典取值,严格匹配action_type,不会出现包含匹配的错误。
测试后返回结果将与预期一致:['1', '2', '3', '4', 0, '5', '6', '7'](若需要将value转为整数,可修改为int(item.get("value", 0)))。
内容的提问来源于stack exchange,提问作者Ugur Selim Ozen
相关产品推荐
相关产品推荐

