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

如何将edn格式的Malli schema转换为JSON schema?

Malli Schema 转标准JSON Schema实现方案

Malli官方原生内置JSON Schema转换模块,无需依赖第三方工具,直接调用内置API即可完成EDN格式Malli Schema到标准规范JSON Schema的转换。

基础使用步骤

  • 引入转换对应的命名空间
(require '[malli.json-schema :as json-schema])
  • 调用转换API传入目标Schema
    核心转换函数为json-schema/transform,第一个参数传入你定义的EDN格式Malli Schema即可,示例:
;; 示例EDN格式Malli Schema
(def user-schema
  [:map
   [:id int?]
   [:username [:string {:min 3, :max 20}]]
   [:email [:re #"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"]]
   [:age [:int {:min 18}]]
   [:tags [:set keyword?]]
   [:profile [:maybe [:map
                      [:avatar string?]
                      [:bio {:optional true} string?]]]]])

;; 执行转换,返回符合JSON Schema规范的Clojure数据结构
(json-schema/transform user-schema)

如果需要输出为JSON格式字符串,搭配常规JSON序列化库(比如cheshire)处理即可:

(require '[cheshire.core :as json])

;; 输出格式化后的标准JSON字符串
(-> user-schema
    (json-schema/transform {:draft :draft7})
    (json/generate-string {:pretty true}))

常用配置项

调用transform时可以传入第二个参数作为配置,常用配置如下:

  • :draft:指定生成的JSON Schema版本,支持:draft4、:draft6、:draft7、:draft2019-09,默认值为:draft4
    ;; 生成Draft 2019-09版本的JSON Schema
    (json-schema/transform user-schema {:draft :draft2019-09})
    
  • 元信息映射:直接在Malli Schema上添加的:title、:description、:default等元属性,转换时会自动映射为JSON Schema的同名字段,无需额外配置
    (def user-schema-with-meta
      [:map {:title "用户信息" :description "平台注册用户核心信息结构"}
       [:id int?]
       [:username string?]])
    

内置映射规则

默认转换逻辑会自动处理常见Schema语义的映射:

  • 基础类型自动对应:int?/pos-int?等整数类型映射为{"type": "integer"},string?映射为{"type": "string"},boolean?映射为{"type": "boolean"},float?/double?映射为{"type": "number"},:map映射为{"type": "object"},:vector/:sequential映射为{"type": "array"}
  • 校验约束自动映射:Malli中配置的:min、:max、:minLength、:maxLength、:pattern、:enum等约束,会自动转换为JSON Schema对应的校验关键字
  • 可选/可空类型处理:用:optional标记的字段会自动从JSON Schema的required数组中移除,[:maybe ...]包装的可空类型会自动在type列表中追加null

自定义类型适配

如果你的Schema中用到了自定义类型或者自定义谓词,只需要为其实现malli.json-schema/-json-schema多方法,即可生成对应的JSON Schema规则,示例:

;; 给自定义的日期类型指定转换规则
(defmethod json-schema/-json-schema :my/date [_ _ _]
  {:type "string" :format "date-time"})

注意:如果自定义类型/谓词没有实现对应的转换方法,转换时会默认忽略该节点的约束,不会在最终生成的JSON Schema中体现,需要手动补全映射逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 22:24:17