convert bash `ls` output to json array

2020-02-08 05:47发布

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.

11条回答
趁早两清
2楼-- · 2020-02-08 06:05

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";'
查看更多
ら.Afraid
3楼-- · 2020-02-08 06:05

I was also searching for a way to output a Linux folder / file tree to some JSON or XML file. Why not use this simple terminal command:

$ tree --dirsfirst --noreport -n -X -i -s -D -f -o my.xml

so, just the linux tree command, and config your own parameters. Here -X gives XML output! For me, that's OK, and i guess there's some script to convert XML to JSON ..

NOTE: I think this covers the same question.

查看更多
ら.Afraid
4楼-- · 2020-02-08 06:06

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.

查看更多
聊天终结者
5楼-- · 2020-02-08 06:06

Most of the Linux machine already has python. all you have to do is:

python -c 'import os, json; print json.dumps(os.listdir("/yourdirectory"))'

This is for . directory , you can add any path.

查看更多
家丑人穷心不美
6楼-- · 2020-02-08 06:12

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"]
查看更多
仙女界的扛把子
7楼-- · 2020-02-08 06:19

Don't use bash, use a scripting language. Untested perl example:

use JSON;
my @ls_output = `ls`; ## probably better to use a perl module to do this, like DirHandle
print encode_json( @ls_output );
查看更多
登录 后发表回答