英文:
golang how to concatenate []byte key vaules with other variable
问题
如何将变量值连接到字节键值中?
type Result struct {
SummaryID int `json:"summaryid"`
Description string `json:"description"`
}
byt := []byte(`
{
"fields": {
"project": {
"key": "DC"
},
"summary": "Test" + strconv.Itoa(Result.SummaryID),
"description": Result.Description,
"issuetype": {
"name": "Bug"
}
}
}`)
注意:Result.SummaryID
和 Result.Description
的值来自 db.Query()
和 rows.Scan()
。
英文:
How to concatenate variable value into the byte key values ?
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"
}
}
}`)
Note: values of Result.SummaryID
and Result.Description
return from the db.Query()
and rows.Scan()
.
答案1
得分: 3
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字符串。
这里有一个示例,它使用结构体嵌套作为主对象,并在其他地方使用映射来演示两种方法。
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
)
英文:
Go doesn't support string interpolation, so you'll have to use something like fmt.Sprintf
or the template
package if you want to compose strings out of smaller substrings.
You can do the former like so:
var buf bytes.Buffer
byt := []byte(fmt.Sprintf(`
{
"fields": {
"project":
{
"key": "DC"
},
"summary": "Test%d",
"description": "%s",
"issuetype": {
"name": "Bug"
}
}
}`, result.SummaryID, result.Description))
Though I would really advise against it, since the encoding/json
package is designed for safely and sanely outputting JSON strings.
Here's an example that uses struct embedding for the main object, and maps elsewhere to demonstrate both approaches.
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" },
},
});
(note that your type declaration contradicts your JSON example in that the former specifies summaryid
but the latter has summary
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论