Live data from Hacker News

Translate any JSON object into valid Go Struct

jsonstruct.com

1–5 of 5 posts

Re: Translate any JSON object into valid Go Struct

#4
It would be nice if it could detect and handle recursive data structures:

  //Field struct
  {
      "id": 0,
      "type": "date",
      "subfields": [
          //Field struct
      ]
  }
this should be translated to:

  type Field struct {
      ID int  `json:id`
      Type string  `json:type`
      Subfields []Field  `json:subfields,omitempty`
  }
instead, it does the following:

  type ExampleStruct struct {
  	  ID        float64 `json:"id"`
  	  Subfields []struct {
  		ID        float64       `json:"id"`
  		Subfields []interface{} `json:"subfields"`
  		Type      string        `json:"type"`
  	} `json:"subfields"`
  	Type string `json:"type"`
  }
It could also be smarter about detecting number types. For example 'ID' came out as float64, and it looks like the tool will never generate int fields, even though a ton of fields are actually 'int' or 'uint' in my experience. Clearly, JSON's 'number' type allows for int values, not just floats, though I'm pretty sure it's either the json package or the reflect.TypeOf() function that always chooses float64 over int.

Personally, I find it more tedious to edit this autogenerated struct, than to just write the struct I want the way it should be in the first place.