Trying to handle Dynamic JSON with static struct

I have JSON data like:
{
“data” : {
“192.168.1.0” : {
“summary” : {
“health” : “excellent”
}
} ,
“192.168.1.1” : {
“summary” : {
“health” : “excellent”
}
}
}
}

I want to create a structure for this JSON data and handle Dynamic type. JSON data would be very large so I don’t want to create map from interface.

What is dynamic in this JSON? What is fixed?

Here the “192.168.0.1” is dynamic it could be any IP.
And rest are fixed

Hi

This is quite tricky but you can do something like this:

https://goplay.space/#gIVxUnFVOmO

You read past some json tokens until you find the host name and then parses the following as a structure. And uses the hostname and the read structure to build a new structure containing host and health. And then continue to the next.

2 Likes

Thanks so much @johandalabacka

1 Like
type Summary struct {
  Health string `json:"health"`
} `json:"summary"`

type Data map[string]Summary  `json:"data"`

So you don’t need to use a map of empty interfaces, but a map of summaries.

Like this:

package main

import (
	"encoding/json"
	"fmt"
)

var b = []byte(`
{
"data" : {
	"192.168.1.0" : {
		"summary" : {
			"health" : "excellent"
		}
	},
	"192.168.1.1" : {
		"summary" : {
			"health" : "excellent"
		}
	}
}
}`)

type Data struct {
    Ips map[string]struct{
	    Summary struct {
	        Health string `json:"health"`
	    } `json:"summary"`
    } `json:"data"`
}

func main() {
	data := Data{}

	_ = json.Unmarshal(b, &data)
	fmt.Printf("%#v\n", data)
}

Check out: https://play.golang.org/p/19HNcB7KsuJ

5 Likes

Yes a much better solution than mine. I learned something new today. Thanks alot!

1 Like

Hi. You could use https://mholt.github.io/json-to-go/
Past your json then refactor the golang output code that fit what you want.
As @acim said the Map should fit well to your needs.

Thanks @inancgumus

Sure thing :slight_smile:

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.