Trying to handle Dynamic JSON with static struct


(Ashtabhuja) #1

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.


(Lutz Horn) #2

What is dynamic in this JSON? What is fixed?


(Ashtabhuja) #3

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


(Johan Dahl) #4

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.


(Ashtabhuja) #5

Thanks so much @johandalabacka


(Boban Acimovic) #6
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.


(Inanc Gumus) #7

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


(Johan Dahl) #8

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


(Onezino Moreira) #9

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.


(Ashtabhuja) #10

Thanks @inancgumus


(Inanc Gumus) #11

Sure thing :slight_smile: