2016-12-14 24 views
-5

如何將變量值連接成字節鍵值?golang如何連接[]字節鍵值與其他變量

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.SummaryID值,並從db.Query()rows.Scan()Result.Description回報。

回答

1

Go不支持字符串插值,因此如果您想要使用較小的子字符串組合字符串,則必須使用類似fmt.Sprintftemplate的程序包。

你可以做以前像這樣:

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" }, 
    }, 
}); 

(請注意,您的類型聲明相矛盾,因爲前者指定summaryid您的JSON的例子,但後者有summary

+0

真棒!精湛的解決方案。愛你!跟上偉大的工作。 – Rocky