0

I am not sure how to do this or word this. I have a variable that returns a string something like this:

unixCommands := exec.Command("ls", "/bin")
unixCommandsout, err := unixCommands.Output()
unixCommandsstring := string(unixCommandsout)
fmt.Printf(unixCommandsstring)

Output:

unicode_start
unicode_stop
unlink
usleep
vi
view
ypdomainname
zcat

I'm looking for creating a JSON array or whatever is easiest to get to this final output:

["unicode_start", "unicode_stop", "unlink", "usleep", "vi", "view", "ypdomainname", "zcat"]

1 Answer 1

1

You can do that with package encoding/json:

outputSlice := strings.Split(unixCommandsstring,"\n")
js,_ := json.Marshal(outputSlice)
fmt.Print(string(js))
Sign up to request clarification or add additional context in comments.

4 Comments

of course in a production system you would actually capture the error from json.Marshal and do something with it :)
@ScallioXTX No, that's not needed here. json.Marshal never fails when passed a string slice.
@rightfold, so you know exactly what the current and all future implementations of JSON marshalling will do for all possible inputs (e.g. unicode, invalid UTF-8, out of memory/buffer, etc, etc)?? It's far easier and better habit to check the error return whenever it is provided. If you think it will never fail then maybe use panic (but in this case of course the os.Exec can fail so the surrounding function will need to return errors anyway). Suggesting that errors can be ignored is foolhardy.
lol, this is a great comment thread "checking errors vs not" =P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.