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

huangapple go评论75阅读模式
英文:

How to remove all spaces, newlines, tabs from byte array?

问题

我正在写一个测试,想要将json.Marshal的结果与一个静态的JSON字符串进行比较:

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

由于json.Marshal的结果中没有任何\n\t和空格,我以为可以简单地使用以下代码来去除所有这些字符:

bytes.Trim(json, " \n\t")

然而,不幸的是,这并不起作用。我可以编写一个自定义的修剪函数并使用bytes.TrimFunc,但这对我来说似乎太复杂了。

除了这种方法,还有什么其他方法可以用尽可能少的代码来实现对JSON字符串的“压缩”?

最好的祝福,
Bo

英文:

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 \n, \t and spaces I thought I could easily do:

bytes.Trim(json, " \n\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

得分: 43

使用任何修剪或替换函数都无法处理JSON字符串中存在空格的情况。这样会破坏数据,例如,如果你有像{"foo": "bar baz"}这样的内容。

只需使用json.Compact函数。

这个函数正好可以满足你的需求,只是它输出到一个bytes.Buffer中。

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

你可以在这里查看一个实际示例:http://play.golang.org/p/0JMCyLk4Sg

英文:

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.

huangapple
  • 本文由 发表于 2014年7月16日 17:27:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/24777101.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定