bash json linux sh ubuntu

convert bash `ls` output to json array

Is it possible to use a bash script to format the output of the ls to a json array? To be valid json, all names of the dirs and files need to be wrapped in double quotes, seperated by a comma, and the entire thing needs to be wrapped in square brackets. I.e. convert:

[email protected]:~/Desktop$ ls
foo.txt bar baz


[ "foo.txt", "bar", "baz" ]

edit: I strongly prefer something that works across all my Linux servers; hence rather not depend on python, but have a pure bash solution.

Use perl as the encoder; it’s guaranteed to be non-buggy, is everywhere, and with pipes, it’s still reasonably clean:

ls | perl -e 'use JSON; @in=grep(s/\n$//, <>); print encode_json(\@in)."\n";'