Skip to content

Instantly share code, notes, and snippets.

@hantuo
Last active December 20, 2016 17:31
Show Gist options
  • Save hantuo/9851dc26b6bf7c90b4f02b1cc8970907 to your computer and use it in GitHub Desktop.
Save hantuo/9851dc26b6bf7c90b4f02b1cc8970907 to your computer and use it in GitHub Desktop.
untyped json unmarshal
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