Last active
December 20, 2016 17:31
-
-
Save hantuo/9851dc26b6bf7c90b4f02b1cc8970907 to your computer and use it in GitHub Desktop.
untyped json unmarshal
This file contains 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" | |
import "fmt" | |
import "strconv" | |
import "reflect" | |
var A = `[1, "2"]` | |
var B = `[3, 4]` | |
var C = `[5, {"a":"b"}]` | |
func Decode(data string) { | |
fmt.Print("decode:", data, " -> ") | |
s := []interface{}{} | |
json.Unmarshal([]byte(data), &s) | |
for _, x := range s { | |
var y float64 | |
switch i := x.(type) { | |
case float64: | |
y = i | |
case string: | |
y, _ = strconv.ParseFloat(i, 64) | |
default: | |
fmt.Println(" unknown type:", reflect.TypeOf(x)) | |
continue | |
} | |
fmt.Print(" ", y) | |
} | |
fmt.Println() | |
} | |
func main() { | |
Decode(A) | |
Decode(B) | |
Decode(C) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment