Please read the question before flagging it.
{
"out_key": {
"some_uri": "url",
"more_than_one_key_here": {
"Ip": "127.0.0.1",
"port": "80",
}
}
}
out_key
is dynamically created. There is no guessing the name of it. Similarly, more_than_one_key_here
is also dynamically created. some_uri
will remain constant under out_key
. In such a scenario, how do I create a struct for decoding the JSON?
You could create a struct for the Ip and Port and a separate one for one of the keys.
type data struct{
Ip string
port string
}
type DynamicKey map[string]data
Then once you decode the json and have the dynamic key, let's say for example it is (rando_key) you can do this
fmt.Println(DynamicKey[rando_key].Ip, DynamicKey[rando_key].port)
This is off course for only one of the keys but it is possible to repeat the process.
In Go field names of a struct have to be known at compile time. So, in your case a struct type is not appropriate. Alternatively, you can use a map.
Let's say, that you are only interested in the IP and port values. Then you can ignore the keys of the JSON object altogether.
package main
import (
"encoding/json"
"fmt"
"log"
)
const data = `{
"out_key": {
"some_uri": "url",
"more_than_one_key_here": {
"Ip": "127.0.0.1",
"port": "80"
}
}
}`
func main() {
m := make(map[string]map[string]interface{})
err := json.Unmarshal([]byte(data), &m)
if err != nil {
log.Fatalf("failed to parse JSON: %v", err)
}
for _, value := range m {
for _, value := range value {
m, ok := value.(map[string]interface{})
if ok {
fmt.Printf("IP: %s
", m["Ip"])
fmt.Printf("Port: %s
", m["port"])
}
}
}
}