dsw7547 2015-06-19 20:35
浏览 30
已采纳

如何插入字节片?

I'm attempting to build a JSON payload for a POST request:

var payload = []byte(`{"foo":"bar", "hello":"world"}`)

However, I would like the values to be interpolated from an existing string. I've tried to use %s, but this is obviously not syntactically correct:

var payload = []byte(`{"foo":%s, "hello":%s}`, val1, val2)

Feels like I'm going about this the entirely wrong way. Any suggestions would be appreciated. Thanks.

  • 写回答

1条回答 默认 最新

  • dsc7188 2015-06-19 20:47
    关注

    To use %s, you need a formatting function.

    var payload = []byte(fmt.Sprintf(`{"foo":%q, "hello":%q}`, val1, val2))
    

    (%q is like %s but adds quotes for you)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?