Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

jeroen@jeroen-ubuntu:~/Desktop$ ls
foo.txt bar baz

to

[ "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.

like image 585
Jeroen Ooms Avatar asked Apr 19 '12 18:04

Jeroen Ooms


3 Answers

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"]
like image 96
Ignacio Vazquez-Abrams Avatar answered Oct 16 '22 12:10

Ignacio Vazquez-Abrams


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'

like image 37
bowel Avatar answered Oct 16 '22 13:10

bowel


Hello you can do that with sed and awk:

ls | awk ' BEGIN { ORS = ""; print "["; } { print "\/\@"$0"\/\@"; } END { print "]"; }' | sed "s^\"^\\\\\"^g;s^\/\@\/\@^\", \"^g;s^\/\@^\"^g"

EDIT: updated to solve the problem with " and spaces. I use /@ as replacement pattern for ", since / is not a valid character for filename.

like image 30
Tronix117 Avatar answered Oct 16 '22 14:10

Tronix117