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()
.
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
)