r/commandline•
K4lim

Output disc space of folders as JSON

I want to output the size of folders to a json file with the following command

tree -d -JL 3 --charset utf-8 --du $HOME/share >> discspace.json

But the command won't output valid json. Instead it outputs following:

[
  {"type":"link","name":"/home/user/share","contents":[
    {"type":"directory","name":"folder1","size":16384,"contents":[
      {"type":"directory","name":"folder1_1","size":4096,"contents":[]},
      {"type":"directory","name":"folder1_2","size":4096,"contents":[]},
      {"type":"directory","name":"folder1_3","size":4096,"contents":[]}>>,<<
    ]},
    {"type":"directory","name":"folder2","size":20480,"contents":[
      {"type":"directory","name":"folder2_1","size":4096,"contents":[]},
      {"type":"directory","name":"folder2_2","size":8192,"contents":[
        {"type":"directory","name":"folder2_2_1","size":4096,"contents":[]}>>,<<
      ]},
      {"type":"directory","name":"folder2_3","size":4096,"contents":[]}>>,<<
    ]}>>,<<
  ]},
  {"type":"report","size":36881,"directories":9}
]

When validating the json I'm gettings errors because too many commas are used (the ones I marked with >>,<<).

which command would be better/correct? I tried du but couldn't get any good json out of it.

Posted Jul 7, 2018, 11:23 PM UTC · edited

46
AyrA_ch•

While trailing commas are not valid, most parsers will happily accept it. The easiest way to fix this is by using a command like sed which would allow you to replace ,} with } and ,] with ] or by feeding it into a json parser that can also output json.

Of course this will also replace all these occurrences inside of strings but I doubt that in your case this will ever happen.

5
keeto•

tree -d -JL 3 --charset utf-8 --du | sed -zr 's/,(\s*\])/\1/g'

3
K4limOP•

tree -d -JL 3 --charset utf-8 --du | sed -zr 's/,(\s*\])/\1/g'

Perfect, thank you very much!

1
K4limOP•

I just realized that the folder size won't be calculated with its content at all. What would be the correct command for that?

1
lad1337•

I don’t know what you need it for but it reminded me of something that I made https://github.com/lad1337/diskusage maybe that can help

Although I don’t know how that would work with folders

2
iam8up•

Can you use gt5 for this?

1