santhosh-tekuri / jsonschema

JSONSchema (draft 2020-12, draft 2019-09, draft-7, draft-6, draft-4) Validation using Go
Apache License 2.0
957 stars 98 forks source link

Proposal: Add Method to Generate Go Types from JSON Schema #128

Closed suiriass closed 1 year ago

suiriass commented 1 year ago

Background

The jsonschema package provides a powerful tool for validating JSON data against a schema. However, it currently lacks the ability to generate Go types from a JSON Schema.

Proposal

I propose to add a new method to the jsonschema package that can generate a map[string]interface{} or []interface{} object from a JSON Schema. This object would represent the structure of the JSON data as defined by the schema, with each field having the correct Go type.

This would look something like this:

// Load a JSON Schema from a file
schema, err := jsonschema.Load("schema.json")
if err != nil {
    // handle error
}

// Generate a Go object from the schema
obj, err := schema.GenerateGoObject(jsondata)
if err != nil {
    // handle error
}

// obj is now a map[string]interface{} or []interface{} that matches the structure of the schema

This feature would complement the existing functionality of the encoding/json package in the Go standard library. While encoding/json can decode JSON data into a map[string]interface{} or []interface{} object, it does not have the ability to generate such an object from a JSON Schema.

Impact Adding this feature would increase the complexity and maintenance cost of the jsonschema package. However, I believe the benefits would outweigh the costs. This feature would make it easier to work with JSON data in Go, especially in applications that need to handle complex or variable data structures.

I'm looking forward to hearing your thoughts on this proposal.

Thank you.

santhosh-tekuri commented 1 year ago

WONT_FIX

Go Types generation is not the goal of this project. this project only goal is validation.

we have exported Schema struct, so that others can implement go types generation from Schema struct, without worrying about jsonschema implementation.