Skip to content

Wrong typedef output #6

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

Closed
moshe5745 opened this issue Mar 26, 2025 · 3 comments
Closed

Wrong typedef output #6

moshe5745 opened this issue Mar 26, 2025 · 3 comments

Comments

@moshe5745
Copy link

schema := jtdinfer.NewInferrer(jtdinfer.WithoutHints())
.Infer(`{"name":"Joe", "age": 52, "something_optional": true, "something_nullable": 1.1}`).IntoSchema()

j, _ := json.MarshalIndent(schema, "", "  ")
fmt.Println(string(j))

Output:

{
  "type": "string"
}

Am I doing something wrong?

@bombsimon
Copy link
Owner

Hello!

Great question and this might not be obvious, but since you're actually passing a string (of JSON), the idea is to use the InferStrings method.

schema := jtdinfer.
	InferStrings(
		[]string{`{"name":"Joe", "age": 52, "something_optional": true, "something_nullable": 1.1}`},
		jtdinfer.WithoutHints(),
	).
	IntoSchema()
                                                                                                      
j, _ := json.MarshalIndent(schema, "", "  ")
fmt.Println(string(j))

Output:

{
  "properties": {
    "age": {
      "type": "uint8"
    },
    "name": {
      "type": "string"
    },
    "something_nullable": {
      "type": "float64"
    },
    "something_optional": {
      "type": "boolean"
    }
  }
}

The Infer method is used to infer primitive Go types. The first example is inferring an actual string (not a string of JSON). The equivalent for your input would be something like this which also gives the same result:

schema := jtdinfer.
	NewInferrer(jtdinfer.WithoutHints()).
	Infer(map[string]any{
		"name":               "Joe",
		"age":                52,
		"something_optional": true,
		"something_nullable": 1.1,
	}).
	IntoSchema()
                                            
j, _ := json.MarshalIndent(schema, "", "  ")
fmt.Println(string(j))

What's happening under the hood when you call InferStrings is that it first runs json.Unmarsal to a map[string]any and calls Infer with the same inferrer for each line.

@bombsimon
Copy link
Owner

I created #7 which updates the readme and adds more examples, hope that helps!

@moshe5745
Copy link
Author

Totally
Thanks for the help and this package

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

2 participants