Advertisement
darkmist

DecodeJSON.go

Jul 20th, 2017
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 3.70 KB | None | 0 0
  1. // Go offers built-in support for JSON encoding and
  2. // decoding, including to and from built-in and custom
  3. // data types.
  4.  
  5. package main
  6.  
  7. import "encoding/json"
  8. import "fmt"
  9. import "os"
  10.  
  11. // We'll use these two structs to demonstrate encoding and
  12. // decoding of custom types below.
  13. type Response1 struct {
  14.     Page   int
  15.     Fruits []string
  16. }
  17. type Response2 struct {
  18.     Page   int      `json:"page"`
  19.     Fruits []string `json:"fruits"`
  20. }
  21.  
  22. func main() {
  23.  
  24.     // First we'll look at encoding basic data types to
  25.     // JSON strings. Here are some examples for atomic
  26.     // values.
  27.     bolB, _ := json.Marshal(true)
  28.     fmt.Println(string(bolB))
  29.  
  30.     intB, _ := json.Marshal(1)
  31.     fmt.Println(string(intB))
  32.  
  33.     fltB, _ := json.Marshal(2.34)
  34.     fmt.Println(string(fltB))
  35.  
  36.     strB, _ := json.Marshal("gopher")
  37.     fmt.Println(string(strB))
  38.  
  39.     // And here are some for slices and maps, which encode
  40.     // to JSON arrays and objects as you'd expect.
  41.     slcD := []string{"apple", "peach", "pear"}
  42.     slcB, _ := json.Marshal(slcD)
  43.     fmt.Println(string(slcB))
  44.  
  45.     mapD := map[string]int{"apple": 5, "lettuce": 7}
  46.     mapB, _ := json.Marshal(mapD)
  47.     fmt.Println(string(mapB))
  48.  
  49.     // The JSON package can automatically encode your
  50.     // custom data types. It will only include exported
  51.     // fields in the encoded output and will by default
  52.     // use those names as the JSON keys.
  53.     res1D := &Response1{
  54.         Page:   1,
  55.         Fruits: []string{"apple", "peach", "pear"}}
  56.     res1B, _ := json.Marshal(res1D)
  57.     fmt.Println(string(res1B))
  58.  
  59.     // You can use tags on struct field declarations
  60.     // to customize the encoded JSON key names. Check the
  61.     // definition of `Response2` above to see an example
  62.     // of such tags.
  63.     res2D := &Response2{
  64.         Page:   1,
  65.         Fruits: []string{"apple", "peach", "pear"}}
  66.     res2B, _ := json.Marshal(res2D)
  67.     fmt.Println(string(res2B))
  68.  
  69.     // Now let's look at decoding JSON data into Go
  70.     // values. Here's an example for a generic data
  71.     // structure.
  72.     byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
  73.  
  74.     // We need to provide a variable where the JSON
  75.     // package can put the decoded data. This
  76.     // `map[string]interface{}` will hold a map of strings
  77.     // to arbitrary data types.
  78.     var dat map[string]interface{}
  79.  
  80.     // Here's the actual decoding, and a check for
  81.     // associated errors.
  82.     if err := json.Unmarshal(byt, &dat); err != nil {
  83.         panic(err)
  84.     }
  85.     fmt.Println(dat)
  86.  
  87.     // In order to use the values in the decoded map,
  88.     // we'll need to cast them to their appropriate type.
  89.     // For example here we cast the value in `num` to
  90.     // the expected `float64` type.
  91.     num := dat["num"].(float64)
  92.     fmt.Println(num)
  93.  
  94.     // Accessing nested data requires a series of
  95.     // casts.
  96.     strs := dat["strs"].([]interface{})
  97.     str1 := strs[0].(string)
  98.     fmt.Println(str1)
  99.  
  100.     // We can also decode JSON into custom data types.
  101.     // This has the advantages of adding additional
  102.     // type-safety to our programs and eliminating the
  103.     // need for type assertions when accessing the decoded
  104.     // data.
  105.     str := `{"page": 1, "fruits": ["apple", "peach"]}`
  106.     res := Response2{}
  107.     json.Unmarshal([]byte(str), &res)
  108.     fmt.Println(res)
  109.     fmt.Println(res.Fruits[0])
  110.  
  111.     // In the examples above we always used bytes and
  112.     // strings as intermediates between the data and
  113.     // JSON representation on standard out. We can also
  114.     // stream JSON encodings directly to `os.Writer`s like
  115.     // `os.Stdout` or even HTTP response bodies.
  116.     enc := json.NewEncoder(os.Stdout)
  117.     d := map[string]int{"apple": 5, "lettuce": 7}
  118.     enc.Encode(d)
  119. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement