JQ to flatten an array into an object

Viewed 500

I'm having trouble using JQ in what should be a simple task.

Here's a sample JSON:

[
    {
        "title": "channel 1",
        "url": "rtsp://thelink"
    },
    {
        "title": "channel UFO",
        "url": "rtsp://thatlink"
    },
    {
        "title": "channel oreo",
        "url": "rtsp://thatotherlink"
    },
    {
        "title": "channel blabla",
        "url": "rtsp://yetanotherlink"
    },
    {
        "title": "channel potato",
        "url": "rtsp://anotherlinkwhatnow"
    }
]

I'm attempting to flatten the array into a larger one for easier parsing later on low power devices. Here's what it should look like:

{
    "channel 1": "rtsp://thelink",
    "channel UFO": "rtsp://thatlink",
    "channel oreo": "rtsp://thatotherlink",
    "channel blabla": "rtsp://yetanotherlink",
    "channel potato": "rtsp://anotherlinkwhatnow"
}

I won't even pretend to understand the full structure of how JSON works, but with each little problem of this type solved, I come closer to understanding.

Any help appreciated. FWIW, being proficient in PHP I can very simply iterate with a foreach and recreate the new one with each value as a key. But I really wish to better understand how JQ works (not for lack of trying or reading the manual!).

1 Answers

Use map to map the array of objects to key-value pairs based on the fields you're interested in, then add to merge these pairs into an object.

$ jq 'map({(.title): .url}) | add' test.json
{
  "channel 1": "rtsp://thelink",
  "channel UFO": "rtsp://thatlink",
  "channel oreo": "rtsp://thatotherlink",
  "channel blabla": "rtsp://yetanotherlink",
  "channel potato": "rtsp://anotherlinkwhatnow"
}
Related