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
While trailing commas are not valid, most parsers will happily accept it. The easiest way to fix this is by using a command like
sedwhich 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.