Json
This commit is contained in:
parent
55978b5df2
commit
6478ac9deb
1
.gitignore
vendored
1
.gitignore
vendored
@ -40,3 +40,4 @@ shadir/shadir
|
||||
shadirconcurrent/shadirconcurrent
|
||||
pinger/pinger
|
||||
datediff/datediff
|
||||
example-json/example-json
|
||||
|
80
example-json/main.go
Normal file
80
example-json/main.go
Normal 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)
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user