tripathiab
(Ashtabhuja)
February 5, 2019, 12:51pm
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.
lutzhorn
(Lutz Horn)
February 5, 2019, 1:08pm
2
What is dynamic in this JSON? What is fixed?
tripathiab
(Ashtabhuja)
February 5, 2019, 2:57pm
3
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
tripathiab
(Ashtabhuja)
February 5, 2019, 6:19pm
5
Thanks so much @johandalabacka
1 Like
acim
(Boban Acimovic)
February 6, 2019, 11:08am
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.
inancgumus
(Inanc Gumus)
February 6, 2019, 8:52pm
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
5 Likes
Yes a much better solution than mine. I learned something new today. Thanks alot!
1 Like
heatbr
(Onezino Moreira)
February 7, 2019, 12:51pm
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.
system
(system)
Closed
May 9, 2019, 7:07pm
12
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.