Rome
Rome

Reputation: 442

Getting variable from jq.exe output in Windows batch reading JSON

I managed having a JSON file created by ffprobe which contains basic info about a video stream in a MKV container. By jq-win64.exe "[.format.duration]" %%~ni.mkv.json the duration of the movie is read correctly from the file and jq echos ["1:36:55.184000"]. Now I want to store this value in a global variable of my script for further processing. I tried several approaches but each of them led to errors and/or left %duration% empty. I tried e.g.

   for %%i in (*.mkv) do (
      SETLOCAL ENABLEDELAYEDEXPANSION
      for /F "tokens=* USEBACKQ" %%F IN ('_tools\jq\jq-win64.exe "[.format.duration]" %%~ni.mkv.json') DO (SET duration=%%F)
      echo Duration is: %duration%
      ENDLOCAL
   ) 

but could not manage to echo %duration%. I think it can't be that hard, most likely I don't do the syntax right on Windows batch. Any ideas? Here is the JSON file as well:

{
    "format": {
        "filename": "TestFile_1080p_26Mbs_8bit_BT709.mkv",
        "nb_streams": 1,
        "nb_programs": 0,
        "format_name": "matroska,webm",
        "format_long_name": "Matroska / WebM",
        "start_time": "0:00:00.000000",
        "duration": "1:36:55.184000",
        "size": "17.586597 Gibyte",
        "bit_rate": "25.978148 Mbit/s",
        "probe_score": 100,
        "tags": {
            "title": "TestFile",
            "encoder": "libmakemkv v1.14.4 (1.3.5/1.4.7) win(x64-release)",
            "creation_time": "2019-08-17T21:01:18.000000Z"
        }
    }
}

Upvotes: 0

Views: 1638

Answers (2)

Reino
Reino

Reputation: 3443

If all you want is the duration, then there's no need for intermediate JSONs, because FFprobe can also tell you that:

ffprobe.exe -v 0 -i <input> -show_entries format=duration -of compact=p=0:nk=1
1:36:55.184000

Create a variable:

FOR /F "delims=" %%A IN (
  'ffprobe.exe -v 0 -i <input> -show_entries format=duration -of compact=p=0:nk=1'
) DO SET duration=%%A
SET duration=1:36:55.184000

If you still want to parse FFprobe's JSON, then there's no need to create json-files either, as you can simply pipe it to JQ instead:

ffprobe.exe -v 0 -i <input> -show_format -of json | jq.exe -r .format.duration
1:36:55.184000

Create a variable:

FOR /F "delims=" %%A IN (
  'ffprobe.exe -v 0 -i <input> -show_format -of json ^| jq.exe -r .format.duration'
) DO SET duration=%%A
SET duration=1:36:55.184000

Upvotes: 0

Compo
Compo

Reputation: 38654

Here's a solution based upon my understanding after the comments:

    For /F Tokens^=2Delims^=^" %%F In (
        '_tools\jq\jq-win64.exe "[.format.duration]" "%%~ni.mkv.json" 2^>NUL')Do (
        Set "duration=%%F"
        SetLocal EnableDelayedExpansion
        Echo( !duration!
        EndLocal
    )

Upvotes: 1

Related Questions