Search code examples
jsonjqmediainfo

Building valid JSON playlist from directory of files using MediaInfo Command Line and jq


I'm using MediaInfo command line v18.08 on ubuntu to parse multiple files in a directory and output JSON, like this: mediainfo * --output=JSON

Which outputs the following JSON for each file (trimmed down a bit)

{
    "media": {
        "@ref": "openingmusic.mp3",
        "track": [
            {
                "@type": "General",
                "Duration": "17.789",
                "Encoded_Library": "LAME3.98r"
            },
            {
                "@type": "Audio",
                "Format": "MPEG Audio",
                "Encoded_Library_Settings": "-m s -V 2 -q 3 -lowpass 18.6 --vbr-old -b 32"
            }
        ]
    }
}

But I only want a subset of that JSON, so I used jq-1.5-1

mediainfo *.mp3 --output=JSON | jq '. | {duration: .media.track[0].Duration, pubDate: .media.track[0].File_Modified_Date_Local, url: .media."@ref"}'

Great, except there's no , between the elements, the whole lot isn't wrapped in [], and of course, while I can fudge that part, if I join the output, I get a trailing comma.

What's the proper jq way of doing this, please?


Solution

  • You can use the --slurp option:

    • --slurp/-s:
      Instead of running the filter for each JSON object in the input, read the entire input stream into a large array and run the filter just once.

    combined with a map to run your filter on each element of the array: jq -s 'map({duration: .media.track[0].Duration, pubDate: .media.track[0].File_Modified_Date_Local, url: .media."@ref"})'

    Then the output will still be an array.