gpt4 book ai didi

golang 如何将 []byte key vaules 与其他变量连接起来

转载 作者:数据小太阳 更新时间:2023-10-29 03:47:09 24 4
gpt4 key购买 nike

如何将变量值连接到字节键值中?

type Result struct {
SummaryID int `json:"summaryid"`
Description string `json:"description"`
}

byt := []byte(`
{
"fields": {
"project":
{
"key": "DC"
},
"summary": "Test" + Result.SummaryID,
"description": Result.Description,
"issuetype": {
"name": "Bug"
}
}
}`)

注意:Result.SummaryIDResult.Description 的值从 db.Query()rows.Scan 返回()

最佳答案

Go 不支持字符串插值,所以你必须使用类似 fmt.Sprintf 的东西或 template如果您想用更小的子字符串组成字符串,请打包。

你可以像这样做前者:

var buf bytes.Buffer
byt := []byte(fmt.Sprintf(`
{
"fields": {
"project":
{
"key": "DC"
},
"summary": "Test%d",
"description": "%s",
"issuetype": {
"name": "Bug"
}
}
}`, result.SummaryID, result.Description))

虽然我真的不建议这样做,因为 encoding/json包专为安全、理智地输出 JSON 字符串而设计。

Here's an example它对主要对象使用结构嵌入,并映射到其他地方以演示这两种方法。

type WrappedResult struct {
Project map[string]string `json:"project"`
Result
IssueType map[string]string `json:"issuetype"`
}

byt, err := json.MarshalIndent(map[string]interface{}{
"fields": WrappedResult{
Result: result,
Project: map[string]string{ "key": "DC" },
IssueType: map[string]string{ "name": "Bug" },
},
});

(请注意,您的类型声明与您的 JSON 示例相矛盾,因为前者指定了 summaryid 但后者具有 summary)

关于golang 如何将 []byte key vaules 与其他变量连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41146072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com