How to remove all spaces, newlines, tabs from an array of bytes?

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 a result, json.Marshal has no \n , \t and spaces, which 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 it seems complicated to me.

What else can I do to make the json string β€œcompressed” with less code?

Best, Bo

+7
json go
source share
1 answer

Using any trim or replace function will not work if there are spaces inside the JSON strings. You would tear 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 bytes.Buffer to 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.

+12
source share

All Articles