Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

go

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

like image 342
bodokaiser Avatar asked Jul 16 '14 09:07

bodokaiser


1 Answers

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.

like image 188
SirDarius Avatar answered Oct 12 '22 01:10

SirDarius