gradio 输入json, 输出json 的示例

	import gradio as gr
        import json

        import gradio as gr
        import json

        # 处理函数接收的是 原生Python字典(JSON对象),无需json.loads
        def process_json(input_json: dict) -> dict:
            try:
                # 业务逻辑:直接操作字典,示例新增字段
                output_json=input_json.copy()
                output_json["processed"] = True
                output_json["note"] = "这是原生JSON对象处理结果"
                return output_json  # 返回字典,Gradio自动转为JSON展示
            except Exception as e:
                # 异常返回JSON格式的错误信息
                return {"error": f"处理失败: {str(e)}"}

        # 构建界面,用gr.JSON作为输入输出
        with gr.Blocks(title="原生JSON处理器") as demo:
            gr.Markdown("# 原生JSON输入输出工具")
            # gr.JSON 组件:支持可视化编辑JSON,直接返回字典
            input_json=gr.JSON(label="输入JSON对象", value={"name": "test", "data": [1,2,3]})
            output_json=gr.JSON(label="输出JSON对象")

            submit_btn=gr.Button("处理JSON")
            submit_btn.click(
                fn=process_json,
                inputs=[input_json],
                outputs=[output_json]
            )

        # 启动服务
        if __name__ == "__main__":
            demo.launch(server_name="0.0.0.0", server_port=9002)

posted on 2026-01-15 15:03  张博的博客  阅读(3)  评论(0)    收藏  举报

导航