如何访问未知键的值?

How to access the value of an unknown key?

我有以下 JSON 文件

{
    "https://test.com/gg": [
        "msg",
        "popup",
        "url"
    ]
}

我想实现的是解析值输出如下

https://test.com/gg?msg=gg
https://test.com/gg?popup=gg
https://test.com/gg?url=gg

我假设它可以使用 jq 来完成,但我不确定如何。

我知道的方式是如果元素被命名为如下所示:

{
    "url":"https://test.com/gg": [
        "p1":"msg",
    ]
}

我会提取如下元素:

cat json | jq "url.[p1]"

但我的情况是没有命名。

jq --raw-output 'to_entries[0] | .key as $url | .value[] | "\($url)?\(.)=gg"' <your json file here>

在哪里

  1. to_entries[0] 产生 {"key":"https://test.com/gg","value":["msg","popup","url"]}
  2. (保存 .key as $url 以备后用)
  3. 然后使用 .value[]
  4. “发出”所有值
  5. 对于每个“发出的”值,生成字符串 "\($url)?\(.)=gg",其中 . 是当前值