0

I want to dynamically define structs in a Go project based on a JSON file.

For example, if I had a json file like so...

{
  "date": "today",
  "time": 12,
  "era": "never",
  "alive": true
}

Then I would expect a struct to be generated (that would look) like this (but not explicitly defined in the source code)...

type DynamicJSON struct {
  date, era string
  time int
  alive bool
}

Furthermore, I want to nest JSON objects such that I could do something like this...

{
  "date": "today",
  "time": 12,
  "era": "never",
  "alive": true,
  "nested": {
    "date": "tomorrow",
    "alive": true
  }
}

...which would actually generate two different structs, like this...

type DynamicJSON1 struct {
      date, era string
      time int
      alive bool
}


type DynamicJSON2 struct {
      date string
      alive bool
}

Is this something that is currently supported?

3
  • I believe you cannot dynamically, at runtime, define types in Go. The next best option would be to use code generation. Commented Oct 28, 2017 at 23:12
  • What result do you want to achieve? Commented Oct 29, 2017 at 5:47
  • If you really unstructured data you can unmarshal it into maps like map[string]interface{} Commented Oct 29, 2017 at 7:02

1 Answer 1

2

I can't garantantee final result, but easyjson does exactly what you asking.

easyjson aims to keep generated Go code simple enough so that it can be easily optimized or fixed. Another goal is to provide users with the ability to customize the generated code by providing options not available with the standard encoding/json package, such as generating "snake_case" names or enabling omitempty behavior by default.

Sign up to request clarification or add additional context in comments.

1 Comment

@kendall-weihe, for one-off gigs, you can use github.com/mholt/json-to-go, which also has a readily working site which would generate a set of Go types from the JSON samples you throw at it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.