【问题标题】:Including empty JSON values in jq output在 jq 输出中包含空 JSON 值
【发布时间】:2021-06-15 13:20:57
【问题描述】:

我正在尝试获取包含偶尔空值的 .csv。

调用此 API (https://www.campaignmonitor.com/api/subscribers/#getting-subscribers-details) 我得到以下信息:

[
    {
        "ID": "fc0ce7105baeaf97f47c99be31d02a91",
        "Type": "Campaign",
        "Name": "Campaign One",
        "Actions": [
            {
                "Event": "Open",
                "Date": "2010-10-12 13:18:00",
                "IPAddress": "192.168.126.87",
                "Detail": ""
            },
            {
                "Event": "Click",
                "Date": "2010-10-12 13:16:00",
                "IPAddress": "192.168.126.87",
                "Detail": "https://example.com/post/12323/"
            }
        ]
    }
    {
        "ID": "dsadsamdkl9309ujd432",
        "Type": "Campaign",
        "Name": "Campaign Two",
        "Actions": []
    }
]

我想得到什么输出:

"Campaign One","Open"
"Campaign One","Click"
"Campaign Two","none"

我目前得到的

"Campaign One","Open"
"Campaign One","Click"

"Actions" == [] 时我似乎找不到包含值的方法

到目前为止我尝试了什么:

尝试 1:

curl -u "apikey:x" https://api.createsend.com/api/v3.2/subscribers/listID/history.json?email=example@email.com | jq -r '.[] | .Name as $n | .Actions[] | ([$n, .Event | if . == null then "none" else . end]) | @csv'

尝试 2:

curl -u "apikey:x" https://api.createsend.com/api/v3.2/subscribers/listID/history.json?email=example@email.com | jq -r '.[] | .Name as $n | .Actions[] | ([$n, .Event // "none"]) | @csv'

尝试 3:

curl -u "apikey:x" https://api.createsend.com/api/v3.2/subscribers/listID/history.json?email=example@email.com | jq -r '.[] | .Name as $n | .Actions[] |.Actions[] | if . == [] then .Actions[].Event = "" else . end | ([$n, .Event]) | @csv'

【问题讨论】:

    标签: json bash shell export-to-csv jq


    【解决方案1】:

    alternative operator //

    jq -r '.[] | (.Actions[].Event // "none") as $e | [ .Name, $e ] | @csv'
    

    这假设第 20 行缺少的逗号已经插入。

    【讨论】:

    • 我很接近,但你澄清了我对jq 的困惑,谢谢!
    猜你喜欢
    • 2023-03-15
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多