Go by Example: JSON

https://gobyexample.com/json


Go by Example: JSON

Go offers built-in support for JSON encoding anddecoding, including to and from built-in and customdata types.

 
 
package main
 
import "encoding/json"
import "fmt"
import "os"

We’ll use these two structs to demonstrate encoding anddecoding of custom types below.

type Response1 struct {
    Page   int
    Fruits []string
}
type Response2 struct {
    Page   int      `json:"page"`
    Fruits []string `json:"fruits"`
}
 
func main() {

First we’ll look at encoding basic data types toJSON strings. Here are some examples for atomicvalues.

    bolB, _ := json.Marshal(true)
    fmt.Println(string(bolB))
 
    intB, _ := json.Marshal(1)
    fmt.Println(string(intB))
 
    fltB, _ := json.Marshal(2.34)
    fmt.Println(string(fltB))
 
    strB, _ := json.Marshal("gopher")
    fmt.Println(string(strB))

And here are some for slices and maps, which encodeto JSON arrays and objects as you’d expect.

    slcD := []string{"apple", "peach", "pear"}
    slcB, _ := json.Marshal(slcD)
    fmt.Println(string(slcB))
 
    mapD := map[string]int{"apple": 5, "lettuce": 7}
    mapB, _ := json.Marshal(mapD)
    fmt.Println(string(mapB))

The JSON package can automatically encode yourcustom data types. It will only include exportedfields in the encoded output and will by defaultuse those names as the JSON keys.

    res1D := &Response1{
        Page:   1,
        Fruits: []string{"apple", "peach", "pear"}}
    res1B, _ := json.Marshal(res1D)
    fmt.Println(string(res1B))

You can use tags on struct field declarationsto customize the encoded JSON key names. Check thedefinition of Response2 above to see an exampleof such tags.

    res2D := &Response2{
        Page:   1,
        Fruits: []string{"apple", "peach", "pear"}}
    res2B, _ := json.Marshal(res2D)
    fmt.Println(string(res2B))

Now let’s look at decoding JSON data into Govalues. Here’s an example for a generic datastructure.

    byt := []byte(`{"num":6.13,"strs":["a","b"]}`)

We need to provide a variable where the JSONpackage can put the decoded data. Thismap[string]interface{} will hold a map of stringsto arbitrary data types.

    var dat map[string]interface{}

Here’s the actual decoding, and a check forassociated errors.

    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }
    fmt.Println(dat)

In order to use the values in the decoded map,we’ll need to cast them to their appropriate type.For example here we cast the value in num tothe expected float64 type.

    num := dat["num"].(float64)
    fmt.Println(num)

Accessing nested data requires a series ofcasts.

    strs := dat["strs"].([]interface{})
    str1 := strs[0].(string)
    fmt.Println(str1)

We can also decode JSON into custom data types.This has the advantages of adding additionaltype-safety to our programs and eliminating theneed for type assertions when accessing the decodeddata.

    str := `{"page": 1, "fruits": ["apple", "peach"]}`
    res := Response2{}
    json.Unmarshal([]byte(str), &res)
    fmt.Println(res)
    fmt.Println(res.Fruits[0])

In the examples above we always used bytes andstrings as intermediates between the data andJSON representation on standard out. We can alsostream JSON encodings directly to os.Writers likeos.Stdout or even HTTP response bodies.

    enc := json.NewEncoder(os.Stdout)
    d := map[string]int{"apple": 5, "lettuce": 7}
    enc.Encode(d)
}
 
$ go run json.go
true
1
2.34
"gopher"
["apple","peach","pear"]
{"apple":5,"lettuce":7}
{"Page":1,"Fruits":["apple","peach","pear"]}
{"page":1,"fruits":["apple","peach","pear"]}
map[num:6.13 strs:[a b]]
6.13
a
{1 [apple peach]}
apple
{"apple":5,"lettuce":7}

We’ve covered the basic of JSON in Go here, but checkout the JSON and Goblog post and JSON package docsfor more.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值