Skip to content

Instantly share code, notes, and snippets.

@haridas
Created March 30, 2015 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haridas/e03763e81efc05a23900 to your computer and use it in GitHub Desktop.
Save haridas/e03763e81efc05a23900 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
)
type Response struct {
Action string
Node Nodes
}
type Nodes struct {
Key string
Dir bool
Nodes []Node
ModifiedIndex int64
CreatedIndex int64
}
type Node struct {
Key string
Value string
ModifiedIndex int64
CreatedIndex int64
}
type TNode struct {
Nodes
}
func main() {
//js := []byte(`{"nodes": [{"key":"/announce/services/kcmongod/arbiter","value":"172.31.29.189","modifiedIndex":8782649,"createdIndex":8782649}]}`)
//js := []byte(`{"key":"/announce/services/kcmongod","dir":true,"nodes":[{"key":"/announce/services/kcmongod/arbiter","value":"172.31.29.189","modifiedIndex":8782649,"createdIndex":8782649},{"key":"/announce/services/kcmongod/1","value":"172.31.15.203","modifiedIndex":8782670,"createdIndex":8782670},{"key":"/announce/services/kcmongod/2","value":"172.31.44.174","modifiedIndex":8813322,"createdIndex":8813322}],"modifiedIndex":5198946,"createdIndex":5198946}`)
js := []byte(`{"action":"get","node":{"key":"/announce/services/kcmongod","dir":true,"nodes":[{"key":"/announce/services/kcmongod/arbiter","value":"172.31.29.189","modifiedIndex":8782649,"createdIndex":8782649},{"key":"/announce/services/kcmongod/1","value":"172.31.15.203","modifiedIndex":8782670,"createdIndex":8782670},{"key":"/announce/services/kcmongod/2","value":"172.31.44.174","modifiedIndex":8813322,"createdIndex":8813322}],"modifiedIndex":5198946,"createdIndex":5198946}}`)
//js := []byte(`{"SortAs": "SGML","GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML","Abbrev": "ISO 8879:1986", "Test": {"New": 3}}`)
// Using map to unmarshal the json. Useful if you are interested only some parts of the json.
var objmap map[string]*json.RawMessage
if err := json.Unmarshal(js, &objmap); err != nil {
panic(err)
}
var allNodes Nodes
json.Unmarshal(*objmap["node"], &allNodes)
fmt.Println("All Nodes, Map based unmarshaling: ", allNodes)
// Conventional unmarshaling using proper data structures.
var nodes Response
json.Unmarshal(js, &nodes)
for _, node := range nodes.Node.Nodes {
fmt.Println(node.Value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment