JQ将数组展平为对象

时间:2020-10-09 23:32:17

标签: arrays json jq

我在使用JQ进行简单的任务时遇到了麻烦。

这是一个示例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"
    }
]

我正在尝试将阵列展平为更大的阵列,以便以后在低功耗设备上更容易解析。它应该是这样的:

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

我什至不假装理解JSON工作原理的完整结构,但是解决了这种类型的每个小问题,我就会更加了解。

任何帮助表示赞赏。 FWIW,精通PHP,我可以非常简单地使用foreach进行迭代,并使用每个值作为键来重新创建一个新值。但是我真的很想更好地了解JQ的工作原理(不是因为没有尝试或阅读本手册!)。

1 个答案:

答案 0 :(得分:1)

使用map根据您感兴趣的字段将对象数组映射为键-值对,然后使用add将这些对合并为对象。

$ 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"
}
相关问题