Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Da Mott Man
Aug 3, 2012


Methanar posted:

I want to marshal json into a struct. Given the following json, I've come up with the following struct. But the keys set for tags could actually be anything, not restricted to name or aggregatedBy. How do I represent this in my struct?

code:
[
  {
    "target": "sumSeries(https_metric.*)",
    "tags": {
      "name": "sumSeries(https_metric.*)",
      "aggregatedBy": "sum"
    },
    "datapoints": [
      [
         null,
        1630946310
      ],
      [
        10,
        1630946320
      ]
    ]
  }
]
code:
type graphiteResults []struct {
	Target string `json:"target"`
	Tags   struct {
		Name         string `json:"name"`
		AggregatedBy string `json:"aggregatedBy"`
	} `json:"tags"`
	Datapoints [][]interface{} `json:"datapoints"`
}

This will handle arbitrary json fields if you marshal the extra data in tags to that member.

Go code:
type graphiteResults []struct {
	Target string `json:"target"`
	Tags   struct {
		Name         string `json:"name"`
		AggregatedBy string `json:"aggregatedBy"`
                Extra map[string]interface{} `json:"-"`
	} `json:"tags"`
	Datapoints [][]interface{} `json:"datapoints"`
}

Adbot
ADBOT LOVES YOU

Da Mott Man
Aug 3, 2012


Methanar posted:

So the existence of tags at all is optional. But if it does exist, it's a map of strings with values of also strings.

code:
type graphiteResults[]struct {
	Target string `json:"target"`
	Tags   map[string]interface{} `json:"tags"`
	Datapoints [][]interface{} `json:"datapoints"`
}

Yeah that should work.

Edit:
Actually I think using anonymous structs would work better if Tags is omitted, the other way if Tags always exists but can be empty.

Go code:
type graphiteResults []struct {
	Target     string          `json:"target"`
	Datapoints [][]interface{} `json:"datapoints"`
}

type OptionalTags graphiteResults

func (results graphiteResults) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		OptionalTags
		Tags map[string]interface{}
	}{
		OptionalTags: OptionalTags(results),
		Tags:         map[string]interface{}{"Name": "testing"},
	})
}

Da Mott Man fucked around with this message at 19:19 on Sep 6, 2021

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply