根据字节切片动态解析json指定字段,初学go可以相互多交流,不妥之处请留言说明,我会及时改正
data.json
``` 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
```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))
}
```
结果输出
``` shell
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"}}
```
有疑问加站长微信联系(非本文作者))