2014-07-16 09:27



I am writing a test where I want to compare the result of json.Marshal with a static json string:

var json = []byte(`{
    "foo": "bar"

As the result of json.Marshal does not have any , \t and spaces I thought I could easily do:

bytes.Trim(json, " 

to remove all of these characters. However unfortunately this does not work. I could write a custom trim function and use bytes.TrimFunc but this seems to complicated to me.

What else could I do to have a json string "compressed" with as less code as possible?

Best, Bo

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dsajkdadsa14222 dsajkdadsa14222 7年前

    Using any trimming or replace function will not work in case there are spaces inside JSON strings. You would break the data, for example if you have something like {"foo": "bar baz"}.

    Just use json.Compact.

    This does exactly what you need, except that it outputs to a bytes.Buffer.

    var json_bytes = []byte(`{
        "foo": "bar"
    buffer := new(bytes.Buffer)
    if err := json.Compact(buffer, json_bytes); err != nil {

    See http://play.golang.org/p/0JMCyLk4Sg for a live example.

    点赞 评论 复制链接分享