golang-web参数校验

本文介绍如何使用Go语言中的gojsonschema包进行JSON Schema验证。通过加载schema文件和待验证的JSON文档,可以检查JSON文档是否符合指定的schema规范。此外,还提供了多种语言将JSON转换为JSON Schema的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

golang-web参数校验

json schema
package main

import (
    "fmt"
    "github.com/xeipuuv/gojsonschema"
)

func main() {

    schemaLoader := gojsonschema.NewReferenceLoader("file:///home/me/schema.json")
    documentLoader := gojsonschema.NewReferenceLoader("file:///home/me/document.json")

    result, err := gojsonschema.Validate(schemaLoader, documentLoader)
    if err != nil {
        panic(err.Error())
    }

    if result.Valid() {
        fmt.Printf("The document is valid\n")
    } else {
        fmt.Printf("The document is not valid. see errors :\n")
        for _, desc := range result.Errors() {
            fmt.Printf("- %s\n", desc)
        }
    }
}

json转json-schema

在线转换:https://www.jsonschema.net/homehttps://easy-json-schema.github.io/https://www.liquid-technologies.com/online-json-to-schema-converter

Python转换:

https://github.com/gonvaled/jskematorhttps://github.com/perenecabuto/json_schema_generatorhttps://github.com/rnd0101/json_schema_inferencerhttps://pypi.python.org/pypi/genson/https://pypi.python.org/pypi/skinfer

NodeJS转换:

https://github.com/Nijikokun/generate-schemahttps://github.com/easy-json-schema/easy-json-schema

红宝石:

https://github.com/maxlinc/json-schema-generator

NodeJS:

npm install generate-schema --save

var GenerateSchema = require('generate-schema')

// Capture Schema Output
var schema = GenerateSchema.json('Product', [
    {
        "id": 2,
        "name": "An ice sculpture",
        "price": 12.50,
        "tags": ["cold", "ice"],
        "dimensions": {
            "length": 7.0,
            "width": 12.0,
            "height": 9.5
        },
        "warehouseLocation": {
            "latitude": -78.75,
            "longitude": 20.4
        }
    },
    {
        "id": 3,
        "name": "A blue mouse",
        "price": 25.50,
        "dimensions": {
            "length": 3.1,
            "width": 1.0,
            "height": 1.0
        },
        "warehouseLocation": {
            "latitude": 54.4,
            "longitude": -32.7
        }
    }
])

参考:https://www.ctolib.com/generate-schema.html
json-chema转golang struct: https://zhuanlan.zhihu.com/p/350162109

相关链接

https://www.lsdcloud.com/go/middleware/json-schema.html#_1-什么是jsonhttps://www.cnblogs.com/makelu/p/11828274.htmlhttp://json-schema.org/implementations.html#validator-gohttps://github.com/xeipuuv/gojsonschemahttps://github.com/santhosh-tekuri/jsonschema

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值