如何根据字段名在JSON Schema中自动查找路径并批量修正
问题描述
我用gojsonschema自动生成JSON Schema,但部分字段类型生成错误,需要修正。当前生成的JSON Schema如下:
{ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://github.com/filecoin-project/bacalhau/pkg/model/job", "$ref": "#/$defs/Job", "$defs": { "Deal": { "properties": { "Concurrency": { "type": "integer" }, "Confidence": { "type": "integer" }, "MinBids": { "type": "integer" } }, "additionalProperties": false, "type": "object" }, "Spec": { "properties": { "Engine": { "type": "integer" }, "Verifier": { "type": "integer" } } } } }
目前我通过手动指定字段路径,用sjson库批量修改字段类型,实现代码如下:
func FixJSONSchema() ([]byte, error) { s := jsonschema.Reflect(&model.Job{}) jsonSchemaData, err := json.MarshalIndent(s, "", " ") if err != nil { return nil, fmt.Errorf("error indenting %s", err) } // JSON String jsonString := string(jsonSchemaData) enumTypes := []struct { Name string Path string }{ {Name: "Engine", Path: "$defs.Spec.properties.Engine.type"}, {Name: "Verifier", Path: "$defs.Spec.properties.Verifier.type"}, } for _, enumType := range enumTypes { // Use sjson to find the enum type path in the JSON jsonString, _ = sjson.Set(jsonString, enumType.Path, "string") } return []byte(jsonString), nil }
但我希望只提供字段名数组(比如["Engine","Verifier"]),让工具自动遍历整个JSON Schema结构,找到对应字段的所有路径(如果有多个匹配就返回全部),再完成批量修正。
内容的提问来源于stack exchange,提问作者aronchick
相关产品推荐
相关产品推荐

