convert bash `ls` output to json array

If you know that no filename contains newlines, use jq:

ls | jq -R -s -c 'split("\n")[:-1]'

Short explanation of the flags to jq:

  • -R treats the input as string instead of JSON
  • -s joins all lines into an array
  • -c creates a compact output
  • [:-1] removes the last empty string in the output array

This requires version 1.4 or later of jq. Try this if it doesn't work for you:

ls | jq -R '[.]' | jq -s -c 'add'


Yes, but the corner cases and Unicode handling will drive you up the wall. Better to delegate to a scripting language that supports it natively.

$ ls
あ  a  "a"  à  a b  私
$ python -c 'import os, json; print json.dumps(os.listdir("."))'
["\u00e0", "\"a\"", "\u79c1", "a b", "\u3042", "a"]