This commit is contained in:
Meutel 2017-07-09 09:33:21 +02:00
parent 55978b5df2
commit 6478ac9deb
2 changed files with 81 additions and 0 deletions

1
.gitignore vendored
View File

@ -40,3 +40,4 @@ shadir/shadir
shadirconcurrent/shadirconcurrent
pinger/pinger
datediff/datediff
example-json/example-json

80
example-json/main.go Normal file
View File

@ -0,0 +1,80 @@
package main
import "encoding/json"
import "fmt"
import "os"
import "strings"
type ReturnsData struct {
Returns []float64
Message string `json:"other"`
}
func displayJSON(jsonData string) interface{} {
var obj interface{}
err := json.Unmarshal([]byte(jsonData), &obj)
if err != nil {
panic(err)
}
fmt.Printf("%T\n ", obj)
fmt.Println(obj)
return obj
}
func main() {
displayJSON(`
{
"key": "value",
"keyint": 10,
"key2": "value2"
}
`)
displayJSON(`
[1,2,3,4]
`)
obj := displayJSON(`500`)
v, ok := obj.(float64)
if !ok {
v = 0
}
x := 100 + v
fmt.Println(x)
bs, err := json.Marshal([]int{1, 2, 3})
if err != nil {
panic(err)
}
fmt.Println(string(bs))
err = json.NewEncoder(os.Stdout).Encode([]int{4, 5, 6})
if err != nil {
panic(err)
}
decoded := new(interface{})
err = json.NewDecoder(strings.NewReader(`
{
"key": "value",
"keyint": 10,
"key2": "value2"
}
`)).Decode(decoded)
if err != nil {
panic(err)
}
fmt.Println(*decoded)
returns := new(ReturnsData)
err = json.NewDecoder(strings.NewReader(`
{
"returns": [1,2,3,4],
"other": "plop"
}
`)).Decode(returns)
if err != nil {
panic(err)
}
fmt.Println(*returns)
}