如何将带有 terraform tfsdk 注释和 types.X 类型的结构编组为 JSON?

问题描述 投票:0回答:1

我有一些结构,正在用 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?

go terraform
1个回答
0
投票

您需要一个相应的结构体,其类型可以序列化/反序列化和编组/解组:

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)
© www.soinside.com 2019 - 2024. All rights reserved.