dsgffz2579 2014-07-16 09:27
浏览 1100
已采纳

如何从字节数组中删除所有空格,换行符和制表符?

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, " 
\t")

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

  • 写回答

1条回答 默认 最新

  • dsajkdadsa14222 2014-07-16 09:44
    关注

    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 {
         fmt.Println(err)
    }
    

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

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

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?