top | item 8952378

Translate any JSON object into valid Go Struct

17 points| nevio | 11 years ago |jsonstruct.com | reply

4 comments

order
[+] optymizer|11 years ago|reply
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.

[+] nevio|11 years ago|reply
@optymizer, thank you! I'll see what I can do about that. It's for sure not as good as it can be but this is just first version. I have in plan to get it smarter in some shorter future.
[+] habeyer|11 years ago|reply
I'm obsessed with this. Use it all the time. Love you dev! whoever you are.
[+] aimatt|11 years ago|reply
Saves me from installing extra packages.