Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

from map (bson.M) instead of struct? #123

Open
amills-vibeirl opened this issue Dec 27, 2023 · 0 comments
Open

from map (bson.M) instead of struct? #123

amills-vibeirl opened this issue Dec 27, 2023 · 0 comments

Comments

@amills-vibeirl
Copy link

amills-vibeirl commented Dec 27, 2023

this library seems to work fine with structs, but what about maps like bson.M{}?

For example, this code:

package main

import (
	"encoding/json"
	"fmt"
	"github.com/invopop/jsonschema"
	"go.mongodb.org/mongo-driver/bson"
)

// Define your struct here. This should mirror your JSON data.

type MyData struct {
	Name    string `json:"name"`
	Age     int    `json:"age"`
	Address string `json:"address,omitempty"`
}

func main() {
	// Generate a JSON schema for your struct

	{

		schema := jsonschema.Reflect(&MyData{})

		// Marshal the schema into JSON
		schemaJSON, err := json.MarshalIndent(schema, "", "  ")
		if err != nil {
			panic(err)
		}

		// Print the JSON schema
		fmt.Println(string(schemaJSON))
	}

	{
		var MyData = bson.M{
			"this_is_string": "value",
			"this_is_int":    5,
			"this_is_struct": &MyData{
				Name:    "<name?",
				Age:     0,
				Address: "<address>",
			},
		}
		schema := jsonschema.Reflect(&MyData)

		// Marshal the schema into JSON
		schemaJSON, err := json.MarshalIndent(schema, "", "  ")
		if err != nil {
			panic(err)
		}

		// Print the JSON schema
		fmt.Println(string(schemaJSON))
	}
}

yields this output:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$ref": "#/$defs/MyData",
  "$defs": {
    "MyData": {
      "properties": {
        "name": {
          "type": "string"
        },
        "age": {
          "type": "integer"
        },
        "address": {
          "type": "string"
        }
      },
      "additionalProperties": false,
      "type": "object",
      "required": [
        "name",
        "age"
      ]
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://go.mongodb.org/mongo-driver/bson/primitive/m",
  "$ref": "#/$defs/M",
  "$defs": {
    "M": {
      "type": "object"
    }
  }
}

this schema def is not really correct (or useful at least):

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://go.mongodb.org/mongo-driver/bson/primitive/m",
  "$ref": "#/$defs/M",
  "$defs": {
    "M": {
      "type": "object"
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant