mholt / json-to-go

Translates JSON into a Go type in your browser instantly (original)

Home Page:https://mholt.github.io/json-to-go/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

if second struct's field is float64, then define float64

orestonce opened this issue · comments

  • input
[{
	"UserId" : [ 10 ]
}, {
	"UserId" : [ 12.3 ]
}]
  • current output:
type AutoGenerated []struct {
	UserID []int `json:"UserId"`
}
  • expected output:
type AutoGenerated []struct {
	UserID []float64 `json:"UserId"`
}

This shares the same cause as #26 : the parser only considers the first instance of a key-value pair it encounters. This is time- and space-efficient.

I've been playing with solutions, but they're all complicated.

The way I see it, we need an intermediary AST-like layer (probably) represented as native JavaScript objects/arrays) that contains only type information. As the parser traverses the rest of the available data, it would update/narrow that intermediary type layer, which would then be used to generate the final struct{}s.

Implementing that is probably not trivial.

This requires type precedence rules. In the case of this issue, float wins over int clearly, as would int64 over int, because that information is lost when converting even a well-defined structure to JSON. I suppose interface{} would be needed in the case of #26 because Go can't unmarshal a string into a numeric type, making that the fall-through case.