Skip to content

Instantly share code, notes, and snippets.

@wudi
Created July 31, 2017 09:51
Show Gist options
  • Select an option

  • Save wudi/0e492a33889285280018e2e829f06fe9 to your computer and use it in GitHub Desktop.

Select an option

Save wudi/0e492a33889285280018e2e829f06fe9 to your computer and use it in GitHub Desktop.
demo.go
package main
import (
"encoding/json"
"fmt"
)
type Source struct {
ID string `json:"id"`
Title string `json:"title"`
Types string `json:"type"`
Partition interface{} `json:"partition"`
}
func main() {
jsonStr1 := `{
"id": "node1",
"name": "name1",
"partition": [
"title",
"type",
"value"
]
}`
var s1 Source
if err := json.Unmarshal([]byte(jsonStr1), &s1); err != nil {
panic(err)
}
// 类型推断
if p, ok := s1.Partition.([]interface{}); ok {
for i, v := range p {
fmt.Printf("Index: %d Value: %s\n", i, v)
}
}
jsonStr2 := `{
"id": "node1",
"name": "name1",
"partition": {
"key1": "value1",
"key2": "value2"
}
}`
var s2 Source
if err := json.Unmarshal([]byte(jsonStr2), &s2); err != nil {
panic(err)
}
// 类型推断
if p, ok := s2.Partition.(map[string]interface{}); ok {
for k, v := range p {
fmt.Printf("Key: %s Value: %s\n", k, v)
}
}
}
@wudi
Copy link
Author

wudi commented Jul 31, 2017

Result:

Index: 0 Value: title
Index: 1 Value: type
Index: 2 Value: value
Key: key1 Value: value1
Key: key2 Value: value2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment