Created
March 30, 2015 20:14
-
-
Save haridas/e03763e81efc05a23900 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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