【问题标题】:Using jq to concatenate multiple entries into a single string value?使用 jq 将多个条目连接成单个字符串值?
【发布时间】:2021-06-17 15:58:24
【问题描述】:

我已经尝试了很长一段时间,并且还研究了 stackoverflow 并遇到了这个问题,该问题接近我想要实现的目标: How to combine an array into a single string value when using CSV output in jq?

不过,我的 JSON 输出看起来要复杂得多:

"content": [
{
    "type": "paragraph",
    "content": [
        {
            "type": "inlineCard",
            "attrs": {
            "url": "https://www.myurl.com"
            }
        },
        {
            "type": "text",
            "text": " "
        }
    ]
},
{
    "type": "paragraph",
    "content": [
        {
            "type": "inlineCard",
            "attrs": {
                "url": "https://www.anotherurl.com"
            }
        },
        {
            "type": "text",
            "text": " "
        }
    ]
},
{
    "type": "paragraph",
    "content": [
        {
            "type": "inlineCard",
            "attrs": {
                "url": "https://www.andanotherurl.com"
            }
        },
        {
            "type": "text",
            "text": " "
        }
    ]
}
]

我现在想得到以下结果:

"https://www.myurl.com, https://www.anotherurl.com, https://www.andanotherurl.com"

我尝试了以下方法:

echo $MY_JSON | jq '[ .content[].content[] | select(.type | contains("inlineCard")) | .attrs.url | join(",") ]'

这告诉我

jq: error (at <stdin>:0): Cannot iterate over string ("http://ww...)

谁能帮帮我?谢谢!

【问题讨论】:

    标签: json jq


    【解决方案1】:

    我自己找到了解决方案,诀窍是在将数组发送到join 函数之前结束数组:

    echo $MY_JSON | jq '[ .content[].content[] | select(.type | contains("inlineCard")) | .attrs.url ] | join(",")'
    

    【讨论】:

      猜你喜欢
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-19
      • 2014-03-15
      • 1970-01-01
      • 2023-01-13
      相关资源
      最近更新 更多