Monday, May 6, 2024
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 462  / 2 Years ago, wed, july 13, 2022, 4:52:08

In the interest of standardizing my video library I'm trying to find a way to quickly create a list of files that need to be converted. After looking at this question and its answer (and much googling) I think I have the basics figured out, but I'm having trouble elaborating on the jq section. For reference, the jq command I'm starting with is as follows:



jq -c '.format.filename as $path | 
.streams[]? |
select(.codec_type=="video" and .codec_name!="h264") |
.codec_name as $vcodec |
{video: $vcodec, path: $path}'


and, for simplicity's sake, let's say this is what's being fed to jq:



{
"streams": [
{
"index": 0,
"codec_name": "hevc",
"codec_type": "video"
},
{
"index": 1,
"codec_name": "aac",
"codec_type": "audio"
}
],
"format": {
"filename": "Video.mkv"
}
}


which produces the following output:



{"video":"hevc","path":"./Video.mkv"}


This is great, but I want to go one step further - I would also like to include the codec used for any audio streams. So, given the same input, I would like the following output:



{"video":"hevc","audio":"aac","path":"./Video.mkv"}


How do I accomplish this?


More From » command-line

 Answers
6

To select both audio and video codec types and exclude h264 video:



$ jq '.format.filename as $path |
[.streams[]? | select(.codec_type=="audio"
or (.codec_type=="video"
and .codec_name!="h264")) |
{(.codec_type): .codec_name, $path}] |
group_by(.path) | map(add) | .[]' input.json
$ jq --version
jq-1.5-1-a5b5cbe


If a shell command becomes complex and it takes more than a few lines;
I switch to more verbose Python to manage the complexity:



result = dict(path=data['format']['filename'])
for stream in data['streams']:
if (stream['codec_type'] == 'audio'
or (stream['codec_type'] == 'video'
and stream['codec_name'] != 'h264')):
result[stream['codec_type']] = stream['codec_name'] # last value wins


data is the input (data = json.loads(json_text)) and result is the desired output (print(json.dumps(result))).



It should be relatively straightforward to adapt the above code for your particular case if you are more familiar with an imperative programming in Python than with a more functional style in jq.


[#10832] Friday, July 15, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ingsta

Total Points: 391
Total Questions: 103
Total Answers: 124

Location: Bonaire
Member since Wed, Mar 29, 2023
1 Year ago
;