一、基础json解析


package main

import (
        "log"
        "encoding/json"
)

/*  json解析时需要结构体成员大写开头,不然就被忽略  */
type rtspUrl struct {
    Url   string	
}


func main(){
        var message string = "{\"url\": \"rtsp://192.168.1.156:554/testStream.sdp\"}"
        var mUrl rtspUrl

        json.Unmarshal([]byte(message), &mUrl)
        log.Println("got message:", string(message), "  ", mUrl.Url)
}

结果:

[root@jn json]# go run json.go
2021/09/27 21:08:55 got message: {"url": "rtsp://192.168.1.156:554/testStream.sdp"}    rtsp://192.168.1.156:554/testStream.sdp
[root@jn json]#

二、文件读取json

readConfig.go:

package main

import (
    "log"
    "io/ioutil"
    "encoding/json"
)

/* json解析时需要结构体成员大写开头,不然就忽略解析 ,后面的多余字符串提示 json 对应 key 值(变量不对应时有用) */
type ConfigSt struct {
    Service string `json:"service"`
    Version string `json:"version"`
    Apps    map[string]app `json:"apps"`
}

type app struct {
    Name string `json:"name"`
}

/* json解析时需要结构体成员大写开头,不然就忽略解析 */
func main() {

    log.Println("Config File Read with Json Format~")

    data, err := ioutil.ReadFile("config.json")
    if nil != err  {
        log.Fatalln("ReadFile ERROR:", err)
        return
    } else {
        log.Println("ReadFile OK :\r\n", string(data))
    }

    var appConfig ConfigSt
    err = json.Unmarshal(data, &appConfig)
    if nil != err {
        log.Fatalln("Unmarshal ERROR:", err)
        return
    } else {
        log.Println("service:", appConfig.Service)
        log.Println("version:", appConfig.Version)
        for k, v := range appConfig.Apps {
            log.Println(k, " :", v.Name)
        }
    }
}

config.json:

{
 "service": "appManager",
 "version": "v1.0.1",
 "apps": {
   "game0": {
    "name": "ice game"
   },
   "game1": {
    "name": "fire game"
   }
 }
}

运行:

[root@jn jsonFromFile]# ls
config.json  readConfig.go
[root@jn jsonFromFile]# go run readConfig.go
2021/11/03 19:59:19 Config File Read with Json Format~
2021/11/03 19:59:19 ReadFile OK :
 {
 "service": "appManager",
 "version": "v1.0.1",
 "apps": {
   "game0": {
    "name": "ice game"
   },
   "game1": {
    "name": "fire game"
   }
 }
}

2021/11/03 19:59:19 service: appManager
2021/11/03 19:59:19 version: v1.0.1
2021/11/03 19:59:19 game0  : ice game
2021/11/03 19:59:19 game1  : fire game
[root@jn jsonFromFile]#

三、原生json拉胯,gjson挺好用

package main

import "github.com/tidwall/gjson"

const json = `{"name":{"first":"Janet","last":"Prichard"},"age":47}`

func main() {
        value := gjson.Get(json, "name.last")
        println(value.String())
}