8

GoLand解析json获取指定字段内容

 3 years ago
source link: https://studygolang.com/articles/35052
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

GoLand解析json获取指定字段内容

wangcheng · 16天之前 · 618 次点击 · 预计阅读时间 2 分钟 · 大约8小时之前 开始浏览    

根据字节切片动态解析json指定字段,初学go可以相互多交流,不妥之处请留言说明,我会及时改正

data.json

{
    "basic_info":{
        "upload_date":"2021-04-25 14:17:05.974168",
        "device_id":"AUTH",
        "tss":{
            "date":"2021",
            "system_version":{
                "system":"1.7.1",
                "plug":"1.7.3",
                "patch":"1.7.22"
            }
        }
    }
}

code.go

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

/**
 * 获取json字符串中指定字段内容  ioutil.ReadFile()读取字节切片
 * @param    bytes    json字符串字节数组
 * @param    field    可变参数,指定字段
 */
func getJsonField(bytes []byte, field ...string) []byte {
    if len(field) < 1 {
        fmt.Printf("At least two parameters are required.")
        return nil
    }

    //将字节切片映射到指定map上  key:string类型,value:interface{}  类型能存任何数据类型
    var mapObj map[string]interface{}
    json.Unmarshal(bytes, &mapObj)
    var tmpObj interface{}
    tmpObj = mapObj
    for i := 0; i < len(field); i++ {
        tmpObj = tmpObj.(map[string]interface{})[field[i]]
        if tmpObj == nil {
            fmt.Printf("No field specified: %s ", field[i])
            return nil
        }
    }

    result, err := json.Marshal(tmpObj)
    if err != nil {
        fmt.Print(err)
        return nil
    }
    return result
}

func main() {
    bytes, _ := ioutil.ReadFile("/tmp/data.json")
    s := getJsonField(bytes, "basic_info", "tss")
    fmt.Println(string(s))
}
root@Sangfor:/tmp/go_code# go run code.go 
{"date":"2021","system_version":{"patch":"1.7.22","plug":"1.7.3","system":"1.7.1"}}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK