我有一些结构,正在用 TF 状态的数据填充。这些结构使用 types.X 类型并具有 tfsdk 注释。当我尝试将这些结构封送为 JSON 时,所有字段都未填充。
type MyStruct struct {
Foo types.String `tfsdk:"foo"`
}
在创建函数中:
var state MyStruct
req.Plan.Get(&state)
// I want a JSON representation of state
enc, _ := json.Marshal(state)
// fields of enc are empty
如何将 MyStruct 编组为 JSON?
您需要一个相应的结构体,其类型可以序列化/反序列化和编组/解组:
type MyGoStruct struct {
Foo string `json:"foo"`
}
那么你需要两个结构之间的某种转换器。我相信在 Go 中你可以为接口定义这个(类似于 Rust 中的
std::convert::Into
特征),但这可能有点矫枉过正:
func myStructToMyGoStruct(myStruct MyStruct) MyGoStruct {
return MyGoStruct{Foo: myStruct.Foo}
}
请注意,如果您要转换为 TF 类型,那么通常还需要输入
context.Context
并返回 diag.Diagnostics
,但这是从 TF 类型转换。
现在您可以按预期进行序列化和封送:
goState := myStructToMyGoStruct(state)
enc, _ := json.Marshal(goState)