Golang之gjson

gjson主要用于从string和[]byte里取json数据

对于interfacele{}类型,要先强制转换为[]byte或string再用gjson,其实单层json下不如直接强转为map,多层考虑用gjson。

gjson的path写法  mirror.region.regions.#.cluster_name把regions切片里的cluster_name字段取出来组成一个切片。

import "fmt"
import "github.com/tidwall/gjson"
const json = `{"name":[{"first":"Janet","last":"Prichard"}, {"abc": 1, "e" : 2}],"age":47}`

var jsonInterface interface {}


func main() {
	// 1、把string转result,再取数据
	gjson.Parse(json).Get("name")
	// 2、把[]byte转result,再取数据
	gjson.ParseBytes([]byte(json)).Get("name")
	// 3、从string格式的json直接取数据
	v := gjson.Get(json, "name")
	// 4、interface{}要先强制转换为[]byte或string,再用gjson的三种方法(单层不如直接强转为map,多层考虑用gjson)
	gjson.Parse(jsonInterface.(string)).Get("name")
	gjson.ParseBytes(jsonInterface.([]byte)).Get("name")
	gjson.Get(jsonInterface.(string),"name")
	
	if v.String() == "" {
		fmt.Println("nil")
	} else {
		fmt.Println(v.String())
		fmt.Println(v.Type)
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果我们有两个不同的结构体,但是它们有相同的字段名称和类型,我们可以在它们之间复制字段值。在Golang中,可以通过以下两种方法实现这种复制: 1. 使用结构体字面量 我们可以使用结构体字面量来为目标结构体指定值。例如: ```go type Person struct { Name string Age int } type Employee struct { Name string Age int Salary float64 } func main() { person1 := Person{Name: "John", Age: 30} employee1 := Employee{ Name: person1.Name, Age: person1.Age, Salary: 50000.0, } } ``` 在上面的代码中,我们首先创建了一个名为person1的Person结构体,然后为employee1结构体赋值,将person1的Name和Age字段复制到employee1中。 2. 使用反射 使用反射也可以实现结构体字段之间的复制。首先,我们需要创建一个源结构体的副本,然后使用反射来将源结构体的值复制到目标结构体。例如: ```go func CopyFields(source interface{}, dest interface{}) error { sourceVal := reflect.ValueOf(source) destVal := reflect.ValueOf(dest) if sourceVal.Kind() != reflect.Struct || destVal.Kind() != reflect.Struct { return fmt.Errorf("source and destination must be struct types") } for i := 0; i < sourceVal.NumField(); i++ { sourceField := sourceVal.Field(i) if !sourceField.CanInterface() { continue } destField := destVal.FieldByName(sourceVal.Type().Field(i).Name) if !destField.IsValid() { continue } if !destField.CanSet() { continue } if sourceField.Type() != destField.Type() { continue } destField.Set(sourceField) } return nil } ``` 在上述代码中,我们首先检查源和目标变量是否为结构体类型。然后,我们使用反射迭代源结构体的字段,并将相应的值复制到目标结构体的字段中。如果源结构体和目标结构体的字段类型不同,则不复制该字段。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值