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:21

Personnaly, I would code script that would run the command ls, send the output to a file of you choice while parsing the output to make format it to a valid JSON format.

I'm sure that a simple Bash file will do the work.

Bash ouput

查看更多
孤傲高冷的网名
3楼-- · 2020-02-08 06:21

Should be pretty easy.

$ cat ls2json.bash
#!/bin/bash
echo -n '['
for FILE in $(ls | sed -e 's/"/\\"/g')
do
echo -n \"${FILE}\",
done
echo -en \\b']'

then run:

$ ./ls2json.bash > json.out

but python would be even easier

import os
directory = '/some/dir'
ls = os.listdir(directory)
dirstring = str(ls)
print dirstring.replace("'",'"')
查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-02-08 06:27

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'

查看更多
淡お忘
5楼-- · 2020-02-08 06:27

Here's a bash line

echo '[' ; ls --format=commas|sed -e 's/^/\"/'|sed -e 's/,$/\",/'|sed -e 's/\([^,]\)$/\1\"\]/'|sed -e 's/, /\", \"/g'

Won't properly deal with ", \ or some commas in the name of the file. Also, if ls puts newlines between filenames, so will this.

查看更多
放我归山
6楼-- · 2020-02-08 06:27

Can't you use a python script like this?

myOutput = subprocess.check_output["ls"]
output = ["+str(e)+" for e in myOutput]
return output

I didn't check if it works, but you can find the specification here

查看更多
登录 后发表回答