You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据user_input动态过滤JSON配置的fruits字段并保留其余内容

配置fruits字段过滤实现方案

原有代码仅提取过滤后的fruits键值对,未保留配置节点其他字段,正确实现如下:

import json

# 示例输入
user_input = ['Apple','Grapes','Watermelon']
superset_config = """
[   
    {
     "input":"source_1",
     "operation":"add",
     "fruits": {
               "Apple":"Red",
               "Grapes": ["Red","Yellow"],
               "Orange": "Yellow"
               },
        "output":"target_1"
    },
    {
     "input":"source_2",
     "fruits": { "Watermelon":"green"},
     "output":"target_2"
    }    
]
"""

# 解析配置为Python对象
superset_definitions = json.loads(superset_config)
filtered_config = []

for node in superset_definitions:
    # 保留当前节点所有原有字段
    filtered_node = node.copy()
    # 仅过滤fruits字段,保留存在于user_input的条目
    filtered_node["fruits"] = {
        fruit: val for fruit, val in node["fruits"].items()
        if fruit in user_input
    }
    filtered_config.append(filtered_node)

# 如需输出格式化的JSON字符串,和示例效果一致可执行以下代码
# result_str = json.dumps(filtered_config, indent=4, ensure_ascii=False)
# print(result_str)

代码说明

  • 用node.copy()完整保留配置节点的所有原有字段(包括input、operation、output等所有自定义配置)
  • 字典推导式仅过滤fruits字段的条目,逻辑简洁性能更高
  • 最终得到的filtered_config就是符合要求的Python配置对象,可直接后续使用

内容的提问来源于stack exchange,提问作者Matthew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 08:39:01